In Python, a file operation takes place in the following order.
Open a file
Read or write (perform operation)
Close the file
How to open a file?
Python has a built-in function open() to open a file. This function returns a file object, also called a handle, as it is used to read or modify the file accordingly.
f = open("test.txt") # open file in current directory
f = open("C:/Python33/README.txt") # specifying full path
f = open("test.txt") # equivalent to 'r' or 'rt'
f = open("test.txt",'w') # write in text mode
f = open("img.bmp",'r+b') # read and write in binary mode
How to close a file Using Python?
f = open("test.txt")
# perform file operations
f.close()
How to write to File Using Python?
with open("C:/Users/Shalki/Desktop/python/del.txt",'w') as f:
f.write("my first file\n")
f.write("This file\n\n")
f.write("contains three lines\n")
How to read files in Python?
f = open("C:/Users/Shalki/Desktop/python/del.txt",'r')
print(f.read(4)) # read the first 4 data
'This'
print(f.read(4)) # read the next 4 data
' is '
print(f.read()) # read in the rest till end of file
'my first file\nThis file\ncontains three lines\n'
print(f.read()) # further reading returns empty sting
Tell & Seek
print(f.read(8))
print(f.read(8))
f.tell() # get the current file position
f.seek(3) # bring file cursor to initial position
print(f.read(8))
print(f.read()) # read the entire file
Readline
f = open("C:/Users/Shalki/Desktop/python/del.txt",'r')
print(f.readline())
print(f.readline())
print(f.readline())
print(f.readline())