File Handling in Python

Python, like many other programming languages, offers file management and allows users to read and write files, as well as perform a variety of other file-related tasks.

Python processes files differently depending on whether they are text or binary, which is essential. A text file is formed by each line of code, which contains a sequence of characters. A specific character called the EOL or End of Line character, such as the comma, or newline character, is used to end each line in a file. It signals to the interpreter that the current line has ended and that a new one has begun. Let’s start with the files for reading and writing.

Working of open()

We must first open the file before doing any activity on it, such as reading or writing.

In open() required two parameters, first for file name and second for file mode which is depend on what operation we want to execute on that file.

The following modes are supported where:

r: perform a read operation on an existing file.
w: perform a write operation on an existing file. If the file already has data in it, it will be overwritten.
a: To append to an existing file, open it. Existing data will not be overridden.
r+:To read and write data into the file, use the r+ command. The file’s prior data will be overwritten.
w+: This command is used to write and read data. It will override any previously stored information.
a+: Read and append data from a file. Existing data will not be overridden.

Here is my document file named ‘TestDoc.txt’ with some line.

Read data from file

If we want to read file so we have to pass 'r' as file mode in open(). Here some functions with example.

read()

read() used to all text line from file.

>>> f = open('TestDoc.txt','r') 
>>> print(f) 
<_io.TextIOWrapper name='TestDoc.txt' mode='r' encoding='cp1252'>
>>> print(f.read())
This is test document
my name is preeti
this is codeinpocket blog

readline()

When you want to read only first line from file use readline().

>>> f = open('TestDoc.txt','r')
>>> print(f.readline())         
This is test document

Now if you want to read second line from file you have to write readline() again.

>>> f = open('TestDoc.txt','r')
>>> print(f.readline())
This is test document

>>> print(f.readline())
my name is preeti

If you want to print some specific number of character, pass the value in readline().

>>> f = open('TestDoc.txt','r')
>>> print(f.readline(4)) 
This
>>> print(f.readline(7)) 
 is tes

readlines()

Return all lines in the file, as a list where each line is an item in the list object

>>> f= open('TestDoc.txt','r')
>>> f.readlines()
['This is test document\n', 'my name is preeti\n', 'this is codeinpocket blog']

Write data to file

If we want to write file so we have to pass 'w' as file mode in open(). Here some functions with example.

Create empty file

when we give file name in write mode that does not exist then open() automatically create empty file with same name.

>>> f = open('TestDoc1.txt','w') 

write()

write() used to write something into file. When we open file in write mode we have to close file using close()

>>> f1 = open('TestDoc1.txt','w')
>>> f1.write("welcome to codeinpocket")
23
>>> f1.close()

Append data in file

When we write data into file we might be some loss previous data, to avoid that case we have to use append data. to append data in file pass the parameter 'a' as file mode.

>>> f1 = open('TestDoc1.txt','a')       
>>> f1.write("here we are learn file handling") 
31
>>> f1.close() 

writelines()

Open the file with "a" for appending, then add a list of texts to append to the file

>>> f= open('TestDoc.txt','a') 
>>> f.writelines(["See you soon!", "Over and out."])
>>> f.close()

Copy data from one file to another

If you want to copy data from one file and write into another file you can do this by using for loop. You have to open first file in read mode and open second file in write mode.

>>> f = open('TestDoc.txt','r')   
>>> f1 = open('TestDoc1.txt','w')
>>> for data in f:               
...     f1.write(data)
... 
22
18
25
>>> f1.close()

Working with image

when we work with image open() not accept the file mode as we pass in text file mode. With image execute read or write mode in binary format.

Lets we have a nature.jpeg image and we want to copy image with different name.

>>> img = open('nature.jpg','rb')
>>> img2 = open('nat.jpeg','wb')
>>> for i in img:
...     img2.write(i)
... 
>>> img2.close()

In above example we first open file in 'rb' read binary format then write into second file in 'wb' write binary format.

That is it for today, hope it helps.
If you have any suggestion for this article please make a comment in comment section below.

If you like this article, you can buy me a coffee. Thanks!

File Handling in Python

Leave a Reply

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

Scroll to top