Python file handling
Opening the file for reading

To open the file for reading, we use the open command with the name of the file as the first parameter enclosed in single quote and the second parameter, the mode which it is opened

file_handle = open ('<file_name>', '<mode>')
Example : Opening the file for reading
file_handle = open ('/tmp/log.txt', 'r')
Opening the file for writing

To open the file for writing, we use the open command with the name of the file as the first parameter enclosed in single quote and the second parameter, the mode which it is opened

file_handle = open ('<file_name>', '<mode>')
Example : Opening the file for writing
file_handle = open ('/tmp/log.txt', 'w')
Reading the file

To read lines in a file, the file must first be opened and use the readline () method to read a single line.

file_handle = open ('<file_name>', '<mode>')
file_handle.readline ()
To read file line by line, we need to have a for loop
file_handle = open ('<file_name>', '<mode>')
for line in file_handle :
    print (line, end = '\n')
Writing to a file

To write content to a file, the file must first be opened and use the write () method to write.

file_handle = open ('<file_name>', '<mode>')
file_handle.write ("content to write")
Closing a file

All files that are opened for reading or writing needs to be closed at the end. The file is closed using close () function

file_handle.close ()
WITH to handle files
with open ('filename', 'mode') as file_handle :
     read_data = file_handle.read ()
Comments