How to work with a text file in Python?

PythonServer Side ProgrammingProgramming

A text file is any file containing only readable characters. The opposite of text files,"binary" files are any files where the format isn't made up of readable characters. Binary files can range from image files like JPEGs orGIFs, audio files like MP3s or binary document formats like Word or PDF. The main difference between a text file and a binary file is that binary files need special programs (or knowledge of the special format) to make sense. Text files can be edited by any program that edits plain text, and are easy to process in programming languages like Python.

f = open('my_file.txt', 'r+')
f.close()

The above code opens 'my_file.txt' in read mode then stores the data it reads from my_file.txt in my_file_data and closes the file. Files are opened in text mode by default in Python and can be directly read/written. The read function reads the whole file at once. You can use the following to read the file line by line:

f = open('my_file.txt', 'r+')
f.close()
f =open("my_file.txt", "w")
f.close()