File handling is one of the important feature in programming languages. Python provides a way to handle(read, write & modify) both text files as well as binary files. This tutorial will cover peek(), write(), writelines(), flush() and close() functions in detail.
➠ There are various functions available in Python for File handling. Click the function to get more detail about that function.
fileVar = open("/complete_path_to_file/pythonTest.txt", "rb")
print(fileVar.peek().decode('utf-8'))
print(fileVar.tell())
Output:
Line 1: This is Python File Handling
Line 2: This is Python File Handling Testing File
0 #Even after peeking the data, position of cursor is Zero
fileVar = open("/complete_path_to_file/pythonTestWrite.txt", "w")
fileVar.write('This is Python File Writing')
fileVar.close()
Output:
27
*******pythonTestWrite.txt content********
This is Python File Writing
******************************************
fileVar = open("/complete_path_to_file/pythonTestWrite.txt", "w")
fileVar.write('This is Python File Writing')
fileVar.write('\nThis is Python\'s second File Writing line')
fileVar.close()
Output:
27
41
*******pythonTestWrite.txt content********
This is Python File Writing
This is Python's second File Writing line
******************************************
fileVar = open("/complete_path_to_file/pythonTestWritelines.txt", "w")
file_str='''This is First Line
This is Second Line
This is third Line'''
fileVar.writelines(file_str)
fileVar.close()
Output:
57
*******pythonTestWritelines.txt content********
This is First Line
This is Second Line
This is third Line
***********************************************
file_list =['This is First Line','This is Second Line', 'This is third Line' , 'This is fourth Line']
fileVar = open("/complete_path_to_file/pythonTestWritelines.txt", "w")
fileVar.writelines(i+'\n' for i in file_list)
fileVar.close()
Output:
*******pythonTestWritelines.txt content********
This is First Line
This is Second Line
This is third Line
This is fourth Line
***********************************************
fileVar = open("/complete_path_to_file/pythonTestWrite.txt", "w")
fileVar.write('This is Python File Writing example for flush()')
fileVar.flush()
fileVar = open("/complete_path_to_file/pythonTestWrite.txt", "w")
fileVar.write('This is Python File Writing')
fileVar.close()