Python File Handling – Create, Open, Read, Append 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 important part of any software and web development in Python. In this tutorial, we'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 files, the first thing you need to do is use 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 to be opened, and the mode indicates that how the file is going to be opened. There are 4 different modes:

  • 'r': Opens a file for reading, error if the file does not exist
  • 'w': Opens a file for writing. Note that the existing file with the same name will be erased. Creates the file if does not exist
  • 'a': Opens a file for appending. Creates the file if 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 is 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 is an example:

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, we can use the open() function with 'w' mode.

The following code opens the file named sample.txt for writing, and create it if 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, it is opened for writing. If it does not exist, the new file will be created, and then you can start writing something to it.

Reading Files

To read a file, we use the open() function with 'r' mode. After the file is opened, you can loop over the file object, or use 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, we 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()

This sample code opens the file sample.txt and if it exists, then reads the first and second line of the file.

Here is an example illustrates how to read all lines of the file using the while loop 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

Reading an Entire File

To read the entire file, we 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, we use the open() function with 'w' mode. After the file is opened, we 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 2 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, we use the open() function with 'a' mode. After the file is opened, we 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 example illustrates 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, we've learned how to create, read, append, and write to files in Python. File handling is one of the most important part of any software and web development in Python. Python provides very useful built-in functions for creating, reading, appending, and writing to files.

Leave a Reply

Your email address will not be published. Required fields are marked *