AppDividend
Latest Code Tutorials

How To Write File In Python | Python File Operations

0

In Python programming, there is no need to import an external library to write files. Python provides the inbuilt function for creating, writing, and reading files. In this example, we will see how to write 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 called EOL (End of Line), which is a new line character (‘\n’) in the 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.

How To Write File In Python

Before we start to write a file, let’s see how to create a file in Python. 

Create a New File

We can create a new file in Python using the open() method, with one of the following parameters:

“x”Create – will create a file, 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, then 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 that we want to open and the string that represents 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 exists, then return FileExistsError: [Errno 17] File exists: ‘sample.txt’.

Now, again, you run the above code, then 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

If we want to write to an existing file, 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, then it will write the “Disney plus is launched in 3 countries” in the already existing sample.txt file.

Notice that we opened a file, written 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()

Now, we have already created a sample.txt file, and already, there is 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 are putting in the line number that we are writing, then putting it in a carriage return and a new line character.

How to close a file in Python

When you are done working, you can use the file.close() command to end things.

What this does is close the file entirely, terminating resources in use, in turn freeing them up for the system to deploy elsewhere. 

It’s important to understand that when you use a f.close() method, any further attempts to use the file object will fail. 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 at the time when a file is no longer needed or if it is to be opened in the different file mode.

How to append data to a file in Python

You can also append the new text to the already existing file or the new 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 the new file.

Python File writelines()

Python file method writelines() 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.

Python’s writelines() method writes the elements of a list to the file.

Where the texts will be inserted depends on a 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.

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

We can open the file using the built-in open() function.

The open() function returns the file object, which has a read() method for reading the content of the file.

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

By default, the Python file read() method returns the whole text, but you can also 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 the files.
  2. You can use the function open(“filename”,”w+”) to create the file. The + tells the python interpreter to open file with read and write the permissions.
  3. You can append data to an existing file use 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 file 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.