Python File Handling

Read and write files


Python file handling: create, open, append, read and write

In Python, there is no need to import an external library to read or write files; Python provides a built-in function for creating, writing and reading files.

Related course: Complete Python Programming Course & Exercises

How to create a text file

With Python, you can create various types of files using code such as .txt , .py, etc., with the following code.

Step 1: Create file

f = open("somefile.txt", "w+")

We declare the variable f to open a file named filename.txt. The open method requires two parameters, the file we want to open and a string that indicates the permissions or actions we want to perform on the file

The "w" in the open parameter means write permission, and the "+" text means the file will be created if the piece does not exist.

Step 2: Write data

 for i in range(10):
     f.write("This is line %d\r\n" % (i+1))

Here's a for loop from 1 to 10.

Using the write() function to enter data into a file

Step 3: Close file

Close the instance of the stored file somefile.txt

f.close()

So to create a new file:

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

How to append data to a file

Step 1: Open file for appending

When you see the "+" sign in the parameters of the open function, it means that a new file will be created if this file does not exist. But it already has that file in the example, so it does not create a new one.

f.open("somefile.txt", "a+")

Step 2: Write data

for i in range(2):
    f.write("Appended line %d\r\n" % (i+1))

This will be written to the file in an add-on mode.

To append to a file

f.open("somefile.txt", "a+")
for i in range(2):
    f.write("Appended line %d\r\n" % (i+1))

How to read files

Step 1: Open file for reading

Change the second parameter in open to "r"

f = open("somefile.txt", "r")

Step 2: Check if file opened

Use the MODE function to check if the file is in open mode.

if f.mode == 'r'

Step 3: Read data

Use the READ method to read file data and store it in variables

contents = f.read()

Finally, you can print this variable to get the text content in the console

To summarize:

f = open("somefile.txt", "r")
if f.mode == 'r'
    contents = f.read()

How to read a file line by line

If the data is too large, it can be read line by line.

f = open("somefile.txt", "r")
f1 = f.readlines
for index in f1:
    print(index)