Topics

Reading and Writing File

Welcome to a tutorial on File Handling Operations in Python. Here you will learn how to read content from a file, write text to any file and how to copy a file's content to another file. You will also be taught how to use tell and seek methods for file handling.

 

Python - Reading a File

The function readline() is used to read a line in the document. Check out the example below:

>>> myFile.readline()

From the code above, the myFile is the instance of the file. The function readline() will just print the whole line starting from the cursor's position.

Now, to order to print the whole content of the file, iterating line by line, the for loop can be used.

for line in myFile:
    # will print all the lines one by one
    print (line)

Aside from making use of iteration, we have another way to read the whole file. When using the readlines() function (you will notice it is readlines, and is different from readline). Using that function will return a list that will contain each line of the file. With this, we should be careful when using this function. However, in situations where a lot of data are in the file, then the list may take up lots of space, thus making the whole reading time longer. In summary, it is recommended to use this function only for reading shorter files that can be stored in a list efficiently.

Also, the function is used quite similar to readlines() only, except that in this scenario we need to store the returned value in some variable.

>>> content = myFile.readlines()

Also, a similar thing can be done manually with the iterative approach:

content = []
for line in myFile:
    content.append(line)

The code above will iteratively append each line of the file on the content list.

 

Python - Writing to a file

The function writes () is used to write a single string into the file. Check out the example below:

>>> content = "Hello, World. I am learning Python."
# In order to write this line in a file
>>> myFile.write(content)

or

>>> myFile.write("Hello, World. I am learning Python")

write’ cannot be used to write the content of a list or tuple. In this case, the writelines() function can be used.

>>> content = ["Python 3.xn", "Hello, World. I am learning Python"]
>>> myFile.writelines(content)

When executing this, it will write the file content with:

Python 3.x
Hello, World. I am learning Python

 

Python - Tell and Seek

Just as discussed above, once a file is opened, there is a cursor that keeps moving once as you read or write. However, it's common to move this cursor around without making any variable read or write at all times, and for this purpose, there is a seek() function available to move to the desired location within a file.

The offset decides how many bytes that need to be skipped, here the second argument start_from is optional, and decides from which place you want to start. The likely values could be any of the following:

0 - Beginning of file

1 - Current position of the file

2 - End of file

Note: in situations where the argument is not being specified by default, it’s 0.

But, if there is a file (file.txt) with the content Hello, World!I.

Now, using the seek function as shown below:

>>> myFile = open('file.txt','r+')
>>> myFile.seek(5)
>>> myFile.read()
', World!'

From the code above, you will notice that the function seek() skipped the first 5 bytes that is 'Hello', and read the next bytes till the end of the line. Now, to get the current position of the pointer, the tell() function can be used. Check below:

>>> myFile.tell()

 

Python - Copying a File

To do this, pick the file to copy and create its object. Also, create another object and use an open() function to create a new file, and writing the path in open() function creates the file if it doesn’t exist. In addition, read() content from the first file, and write() the same in the other file.

>>> file1 = open("original.txt", "r")
>>> file2 = open("duplicate.txt", "w")
>>> l = file1.readline()
>>> while l:
 		file2.write(l)
		l = file1.readline()
>>> file1.close()
>>> file2.close()

Finally, open the file duplicate.txt and you should see the copied text.