File is a named location on disk to store related information. Python uses the file objects to interact with external files on the computer. These files could be of any format like text, binary, excel, audio, video files. Please note external libraries will be required to use some of the file formats.
Typically in python file operation takes place in the following order:
In [1]:
%%writefile test.txt
This is a test file
Python has a built-in function called open() to open a file. This function returns a file handle that can be used to read or write the file accordingly.
Python allows a file to open in multiple modes. The following are some of the modes that can be used to open a file.
In [11]:
# open the file in read mode
# f = open("C:/Python33/test.txt) # opens file in the specified full path
f = open('test.txt','r') # opens file in the current directory in read mode
print(f.writable()) # Is the file writable - False
print(f.readable()) # Is the file readable - True
print(f.seekable()) # Is random access allowed - Must be True
print(f.fileno())
In [ ]:
# Different ways of opening the files
# f = open('test.txt') # equal to 'r' or 'rt' (read text)
# f = open('test.txt','w') # write in text mode
# f = open('image.bmp','r+b') # read and write in binary mode
# using encoding type
# f = open("test.txt", mode="r", encoding="utf-8")
In [17]:
# close the file using close function
f.close()
In [23]:
# Using Exception Method
try:
f = open("test.txt",mode="r",encoding="utf-8")
# perform file operations
f.seek(0)
print(f.read(4))
finally:
f.close()
In [24]:
# Using 'with' Method
# Explicit close is not required. File is closed implicitly when the block inside 'with' is exited.
with open('test.txt',encoding='utf-8') as f:
# perform file operations
print(f.read())
In [34]:
with open('test.txt') as f:
f.seek(0) # move the file pointer to start of the file
print(f.tell())
print(f.read(4)) # read the first 4 words
print(f.tell()) # print the current file handler position
print(f.read()) # read till end of file
print(f.tell())
print(f.read()) # this will print nothing as it reached end of file
print(f.tell())
In [36]:
%%writefile test1.txt
Line 1
Line 2
Line 3
In [45]:
with open('test1.txt') as f:
print(f.readline(), end = '') # Prints the 1st Line
print(f.readline()) # Prints the 2nd Line
print(f.readline()) # Prints the 3rd Line
print(f.readline()) # prints blank lines
print(f.readline())
In [39]:
with open('test1.txt') as f:
print(f.readlines())
In [40]:
# using for loop
for line in open('test1.txt'):
print(line, end='') # end parameter to avoid printing blank lines
In [51]:
with open('newfile.txt','w+') as f:
f.writelines('New File - Line 1')
f.writelines('New File - Line 2')
f.seek(0)
print(f.readlines())
In [56]:
try:
f = open('newfile.txt','a')
f.write('this is appended line')
f.close()
f = open('newfile.txt','r')
print(f.read())
finally:
f.close()