Special Offer - Enroll Now and Get 2 Course at ₹25000/- Only Explore Now!

All Courses
Python Files

Python Files

May 17th, 2019

Python Files

File is a named location in disk to store data. In Python, a file operation takes place in the following order.

  • Open a file
  • Read or write (perform operation)
  • Close the file

Python can process two types of files

  • Text file (default)
  • Binary file

Text file:

A text file is nothing but which is containing alphabates,numbers,symbols,no specific formatings it is called Text file.
Text file contains alphabets , numbers , symbols.

Binary file:

File not readable by human and understandable by machines.

To Open File:

File is opened using open() and it will return file descriptor.

Listed down modes available to open a file

F = open(“test_sample.txt”) #to open file in current directory
F= open(“D:/Documents:/README.txt”) #specifying full path
By default file will be opened in read mode in text format
The default is reading in text mode. In this mode, we get strings when reading from the file.
In open() method explicitly need to mention mode = ‘b’ if you want to open binary files
Example:
images or exe files)

Mode
Description
‘r’

Open a file for reading .If file is not found in specified path ‘FileNotFound’ Exception will be raised.

‘w’

Open a file for writing . If file is not found in specified path , it will create new file .If file is already found in that path , it truncates the file (it will delete all contents from file and will write from beginning of the file).

‘x’

Open a file for exclusive creation .If file is not found , it will create new file .If file already exists it won’t truncate the file instead it will throw error ‘FileExistsError’.

‘a’

Open a file in append mode . If file is not found , it will create new file . If file is already present , file pointer will be moved to the end of the file to perform append operation.

‘w+’

Open a file for reading and writing . If file is not found , it will create new file .If file is already present  the file content will get truncated and opened for reading and writing purpose.

‘r+’

Open a file for reading and writing . If file is not found , it will create new file .If file is already present the file content  will get truncated and  opened for reading and writing purpose.

‘a+’

Open a file for appending and reading . If file is not found , it will create new file .If file is found already , the new contents will get appended to the already existing content in the file (the older contents in file won’t get truncated).

‘wb’

Open a file in binary mode for writing content to file .If file is not found ,a new binary file will get created .If file is already found , it will get truncated.

‘rb’

Open a file in binary mode for reading contents from the file .If file is not found ,FileNotFoundError will be raised .If file is found , it would be used for reading contents from the file.

‘ab’

Open a file in binary mode for appending contents to the file .If file is not found , it will create new file .If file is already found , the newer data will get appended to the already existing content in the file.

‘wb+’

Open a file in binary mode for reading and writing contents to the file It will create new file , if file is not found .If file is found ,it will truncate the content of file and will be used for reading and writing contents.

F = open(“sample_new.txt”) #this as well as mode = ‘r’ both are similar
F= open(“sample_new”,’w’) #performs write operation in text file
F= open(“animal.bmp”,’r+b’) #performs read and write in binary file

To close file:

f.close() ->to perform file close operation
Python will automatically delete all cleanup resources like deleting objects or closing files at the end of our program execution , to avoid data corruption ->programmer need to explicitly close the file.
f.close() ->need to be performed by programmer to ensure that data written to file buffer is flushed to disk (this happens only if the file is closed properly)
f.open(“msg.txt”,’w’)
f.write(“world”)
f.close()
In the above mentioned scenario , there may be chances of exception is raised during file write operations and file is not closed properly.
Better way to achieve this
f = open(“msg.txt”,”w”)
try :
f.write(“Good morning”)
Finally:
f.close()

Writing into a file using write()

Writing into a file is achieved using ‘x’ ,’a’,’w’,’r+’ modes
Return value :Number of bytes written

Code snippet:

with open(“sample_new.txt”,mode=’w’,encoding = ‘utf-8’) as fp:
fp.write(“This is first line\n”)
fp.write(“This is second line”)
fp.write(“This is third line”)
’sample_new.txt’ will get created if it does not exist. If it does exist, it is overwritten , the old content will be truncated

Reading a file using read()

Code snippet:

F=open(“sample_new.txt”,encoding=’utf-8’)
F.read(4)     #reads first 4 bytes —>’This’
F.read(4)     #reads next 4 bytes –>’ is ’
F.read()      #reads the entire content of file from current file pointer
First line
This is second line
This is third line
F.read()      #further reading returns empty string

Moving File point cursor to required location

tell ->returns current file pointer location
Seek(from_what,offset) ->moves file pointer to the location specified

tell()

Returns the current position of file pointer

seek(from_what,offset)

Moves the file pointer to from_what position and then move file pointer to offset mentioned bytes from the file pointer position

f.seek(from_what,offset)
Possible values of from_what
0 ->moves file pointer to begging to file
1 ->moves file pointer to current location
2 ->moves file pointer to end of file
It will move the file pointer to the location based of from_what value and from there file pointer will be moved to number of bytes mentioned as offset.

Example :

f.seek(0,10)
->from starting of file , file pointer f will be moved 10 bytes
f.seek(1,10)
->from current file pointer will be moved 10 bytes
f.tell() ->to get the exact bytes where the file pointer is currently available
To read file contents line by line
Reading a file line by line using for loop

Code Snippet :

with open (“file_context.txt”) as f:
for line in f:
Print(line,end=””)

Output:

This is my first line
This file
Contains three lines

readline()

readline() will read a single line from current file pointer.

Code snippet:

To open a file and read its first and second line using readline()
with open (“file_readline.txt”) as f:
print(f”File first line {f.readline()}”)
print(f”File second line {f.readline()}”)

Output:

File first line This is first line
File second line This is second line

readlines()

readlines() -> to read all lines from file and return it as list.

Code snippet :

With open(“file_sample.txt”)  as f:
Print(f”f.readlines {f.readlines()}”)

Output:
[“This is first line”,”This is second line”,”This is third line”]

Writeline()

To write a single line to the file.

writelines()

writelines() -> to read all lines from file and return it as list.