# 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+')
for line in f.readlines():
print line
f.close()

You can also write to text files. For example, if you want to overwrite my_file.txt, you'd open it in write mode and write to it:

f =open("my_file.txt", "w")
f.write("My File!")
f.close()

You can also append to existing files using the append mode. Opening a file in append mode sets the file pointer to the end of file. Any consequent write statements that are executed add data to the end of the file.

Published on 21-Dec-2017 13:25:16