Python File Handling Operations

In this tutorial, we will learn how to read content from a file, then write text to any file and how to copy a file content to another file. We will also use tell and seek methods for file handling.


Python - Reading a File

Let's start by learning how to read a file.

readline() function is used to read a line in the document. It can be used like:

>>> myFile.readline()

where myFile is the instance of the file. readline() function will simply print the whole line starting from the cursor's position.

In order to print the whole content of the file, iterating line by line, we can use a for loop:

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

Beside using iteration, there is another way of reading the whole file, using readlines() function(notice it is readlines, which is different from readline). Using the function will return a list that will contain each line of the file. Because of this, one should be careful while using this function. In case there is lots of data in the file, the list may take lots of space, and thus making the whole reading time longer. Thus, it is recommended to use this function only for reading shorter files which can be stored in a list efficiently.

It is used pretty much like readlines() only, except that in this case we need to store the returned value in some variable:

>>> content = myFile.readlines()

Similar thing can done manually using iterative approach:

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

This will iteratively append each line of the file on content list.


Python - Writing to a file

write() function is used to write a single string into the file. For example, there is a string

>>> 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 can't be used for writing the content of list or tuple. In such cases, writelines() function is used.


>>> content = ["Python 2.x\n", "Hello, World. I am learning Python"]
>>> myFile.writelines(content)

Executing this will write the file content with:


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


Python - Tell and Seek

As we mentioned before once you open a file there is a cursor that keeps moving once as you read or write. It's sometimes important to move this cursor around without making any variable read or write every time, and for this purpose, there is a seek() function available to move to the desired location within a file.

>>> myFile.seek(offset, [start_from])

offset decides how many bytes you want to skip, here second argument start_from is optional, which decides from which place you want to start. Possible values can be-

  • 0 - Beginning of file
  • 1 - Current position of file
  • 2 - End of file

In case the argument is not being specified, by default, it's 0.

Suppose there is a file(file.txt) with content Hello, World!

Then using the seek function as below:

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

As you can see here, the seek() function skipped first 5 bytes (i.e., 'Hello' and read the next bytes till the end of the line. In order to get the current position of the pointer, tell() function can be used. It will return the byte's pointer is away from the beginning.

>>> myFile.tell()

Python - Copying a File

Pick the file to copy and create its object. Create another object and use open() to create a new file(writing the path in open() function creates the file if it doesn’t exist). read() content from first file. 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()

Open the file duplicate.txt and you should be able to see the copied text.