Python File Handling – Create, Open, Read, and Write

File Handling in Python - How to Create, Read, Append, and Write to a File in Python

File handling is one of the most vital parts of any software and web development in Python. In this tutorial, you'll learn how to create, open, read, append, and write to files in Python.

Python provides built-in functions for creating, reading, appending, and writing files. Before you can read, append or write to a file, the first thing you need to do is to open the file using the Python built-in open() function to get the file object.

Python File Open() Function

The open() function takes two arguments, filename and mode. The filename is the name of the file, and the mode argument indicates what you want to do after you open the file. 

There are four different modes:

  • 'r': Opens a file for reading, error if the file does not exist
  • 'w': Opens a file for writing. The existing file with the same name will be erased and creates the file if it does not exist.
  • 'a': Opens a file for appending and creates the file if it does not exist
  • 'r+': Opens a file for both reading and writing, error if the file does not exist

Remarks

  • The open() function opens a file for reading if the mode omitted
  • You need to close the file after you finish reading, writing, or appending the file. To close the file, you use the close() function.

Here are examples:

reading_file = open('employee_list.txt', 'r') #open a text file for reading
writing_file = open('employee_listsfas.txt', 'w') #open a text file for writing
reading_and_writing_file = open('employee_list.txt', 'r+') #open a text file for reading and writing
appending_file = open('employee_list.txt', 'a') #open a text file for appending

Creating Files

To create a file, you use the open() function with 'w' mode.

The following code opens the file named sample.txt for writing, and create it if it does not exist:

open_file = open("sample.txt", 'w') #open the file for writing. Creates it if does not exist.
open_file.close() #close the file.

If the file sample.txt already exists, open it for writing. If it does not exist, create a new file, and then you can start writing something to it.

Reading Files

To read a file, you use the open() function with 'r' mode. After the file opened, you can loop over the file object, or use the readline() or read() method to read lines from the file.

Reading a Single Line of a File

To read a single line of a file, you use the readline() method.

Here is an example:

reading_file = open('sample.txt', 'r') #open a text file for reading
first_line = reading_file.readline()
second_line = reading_file.readline()
print (first_line, end='')
print (second_line, end='')
reading_file.close()

The above program opens the file sample.txt,and if it exists, then reads the first and second line of the file.

The following illustrates an example of how to read all lines of the file using the while loop statement and readline() method:

reading_file = open('sample.txt''r'#open a text file for reading
while(True):
    line = reading_file.readline()
    print(line, end='')
    if line == "":
        break
reading_file.close() #close the file

If the file sample.txt not exist, Python throws an error as follows:

FileNotFoundError: [Errno 2] No such file or directory: 'sample.txt'

Reading an Entire File

To read the entire file, you use the read() method as illustrated in the following example:

reading_file = open('sample.txt', 'r') #open a text file for reading.
lines = reading_file.read() #read all lines of the file.
print(lines)
reading_file.close() #close the file.

Reading a File by Looping Over the File Object

You can loop over the file object and read all lines from the file as illustrated in the following example:

reading_file = open('sample.txt''r'#open a text file for reading.
for line in reading_file:
    print(line, end='')
reading_file.close() #close the file.

Writing Files - How to Delete Old Content and Update a File in Python

To delete old content and update a file, you use the open() function with 'w' mode. After the file opened, you use the write() method to update the file.

The syntax of the write() method is as follows:

write(string)

The following is an example of writing two lines to the sample.txt file:

writing_file = open("sample.txt", 'w') #open the file for writing. Creates it if does not exist.
first_line = "1- ID: 1001 | Name: Employee 1001 | Department: Sales & Marketing\n"
second_line = "2- ID: 1002 | Name: Employee 1002 | Department: Business Development\n"
writing_file.write(first_line) #writing the first line to the file.
writing_file.write(second_line) #writing the second line to the file.
writing_file.close() #close the file.

Appending Files - Keeping Old Content and Adding New Lines

To keep old content and update an existing file, you use the open() function with 'a' mode. After the file opened, you use the write() method to update the file.

Note that the old content of the file is kept, and any data written to the file will be added at the end of the file.

The following illustrates an example of how to append the existing file:

appending_file = open("sample.txt", 'a') #open the file for writing. Creates it if does not exist.
third_line = "3- ID: 1003 | Name: Employee 1003 | Department: Business Development\n"
fourth_line = "4- ID: 1004 | Name: Employee 1004 | Department: Finance & Accounting\n"
appending_file.write(third_line) #writing the third line to the file.
appending_file.write(fourth_line) #writing the fourth line to the file.
appending_file.close() #close the file.

In this tutorial, you've learned how to create, read, append, and write to files in Python. File handling is one of the most vital parts of any software and web development in Python. Python provides useful built-in functions for creating, reading, appending, and writing to files.


See also:
Python return Statement with Examples
Python List Methods and Functions with Examples
Python abs() – Absolute Value in Python
Python Factorial – Find the Factorial of a Number
Python min() – Find the Smallest Value in Python

Leave a Comment