AppDividend
Latest Code Tutorials

Python write to file: The Complete Guide

Python provides built-in functions for creating, reading, and writing files. Therefore, importing an external library to write files is not necessary. To open a file in Python, use the open() method.

In this example, we will see how to write a file in Python. Two types of files can be handled in Python, standard text files and binary files (written in the binary language, 0s, and 1s).

  1. Text files: In this type of file, each line of text is terminated with the special character EOL (End of Line), a new line character (‘\n’) in Python by default.
  2. Binary files: In this type of file, there is no terminator for the line, and the data is stored after converting it into machine-understandable binary language.

Python write to file

To write to a file in Python, use the file.write() function. The file.write() is a built-in Python function that will create a file if the specified file does not exist and write the provided content inside the file.

Create a new file

To create a new file in Python, use the open() method with one of the following parameters:

For example, “x”Create – will create a file and returns an error if the file exists.

“a”Append – will create a file if the specified file does not exist.

“w”Write – will create a file if the specified file does not exist.

See the following code.

# app.py

f = open("sample.txt", "x")

In the above code, we are creating a file with the parameter ‘x.’ That means if the file already exists, it will return an error. It will create a new empty file is created!

We declared a variable f to open the file named sample.txt. The open() function takes two arguments: the file we want to open and the string representing the kinds of permission or operation we want to do on the file.

Here we used the “x” letter in our argument, which indicates create the file, and if it exists, then return FileExistsError: [Errno 17] File exists: ‘sample.txt”, you rerun the above code, it will give the FileExistsError.

# app.py

f = open("sample.txt", "w")

In the above code, we have passed the “w,” which means it will create a file if it does not exist, and it won’t give any error if the file does not exist.

Write to an existing file in Python

To write to an existing file in Python, you must add the parameter to the open() function:

“a” – Append – It will append to the end of the file.

“w” – Write – It will overwrite any existing content.

See the following code.

# app.py

f = open("sample.txt", "a")
f.write("Disney plus is launched in 3 countries")
f.close()

If you run the above code, it will write the “Disney plus is launched in 3 countries” in the already existing sample.txt file.

Notice that we opened a file, write a file, and then closed a file using the close() function.

Let’s use for loop to write in the file.

# app.py

f = open("sample.txt", "a")
for i in range(11):
     f.write("This is line %d\r\n" % (i+1))
f.close()

We have already created a sample.txt file, and there is already one line of text.

We are now appending 11 more lines, so let’s see the output.

# sample.txt

Disney plus is launched in 3 countriesThis is line 1
This is line 2
This is line 3
This is line 4
This is line 5
This is line 6
This is line 7
This is line 8
This is line 9
This is line 10
This is line 11

We have the for loop that runs over a range of 11 numbers. Using Python, write a function to enter data into the file.

The output we want to iterate in the file is “this is line number“, which we declare with a write function and then percent d (displays integer).

So basically, we put in the line number we are writing, a carriage return, and a new line character.

How to close a file in Python

To close a file in Python, use the file.close() method. What file.close() function does is to close the file entirely, terminating resources in use, freeing them up for the system to deploy elsewhere. 

It’s important to understand that when you use an f.close() method, any further attempts to use the file object will fail. This is because the f.close() function will close the instance of the file sample.txt stored.

f.close()

The file close() function closes a file and frees the memory space acquired by that file.

It is used when a file is no longer needed or if it is to be opened in a different file mode.

How to append data to a file in Python

To append data to a file in Python, use the open() function and pass the “a+” as the second parameter. You can also append the new text to the existing file.

f = open("sample.txt", "a+")

See the following code.

# app.py

f = open("sample.txt", "a+")
for i in range(11):
     f.write("This is line %d\r\n" % (i+1))
f.close()

The plus sign in the code indicates that it will create the new file if it does not exist. But in our case, we already have the file, so we are not required to create a new file.

Python file writelines()

The writelines() is a built-in Python function that writes the sequence of strings to the file. The sequence can be any iterable object producing strings, typically the list of strings. There is no return value. Instead, the writelines() method writes the elements of a list to the file.

The texts will be inserted depending on the file mode and stream position.

  1. “a”: The texts will be inserted at a current file stream position, default at the end of the file.
  2. “w”: The file will be emptied before the texts will be inserted at the current file stream position, default 0.

Syntax

file.writelines(list)

The list parameter is of either text or byte objects that will be inserted.

Example

See the following code.

# app.py

f = open("data.txt", "a")
f.writelines(["\nSee you soon!", "\nPeek-a-boo."])
f.close()

Output

See you soon!
Over and out.

How to read a file in Python

To read a file in Python, use the built-in open() function. The open() function returns the file object, which has a read() method for reading the file’s content.

f = open("filename", "r")

See the following code.

# app.py

f = open("data.txt", "r")
print(f.read())

Output

➜  pyt python3 app.py
See you soon!
Over and out.
➜  pyt

The Python file read() method returns the whole text by default, but you can specify how many characters you want to return.

File Modes in Python

Mode Description
‘r’ This is the default mode. It opens the file for reading.
‘w’ This Mode Opens the file for writing.
If the file does not exist, it creates a new file.
If the file exists, it truncates the file.
‘x’ Creates a new file. If the file already exists, the operation fails.
‘a’ Open file in append mode.
If the file does not exist, it creates a new file.
‘t’ This is the default mode. It opens in text mode.
‘b’ This opens in binary mode.
‘+’ This will open a file for reading and writing (updating).

Summary

  1. Python allows you to read, write and delete files.
  2. You can use the function open(“filename”,”w+”) to create the file. The + tells the python interpreter to read and write the permissions to open the file.
  3. You can append data to an existing file using the command open(“Filename”, “a“).
  4. You can use the read() function to read the ENTIRE contents of a file
  5. You can use the readlines() function to read the content of the files one by one.

Related Posts

File handling in Python

Python file open() function

Python Read and Write CSV file

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.