Let’s say that you need to open, read, and write text files in Python. First you can use the open()
built-in function to open the file. Once the file is opened you can use the two built-in methods read()
and write()
to read from the file and to write to the file.
>>> opened_file = open('file.txt')
>>> the_file_content = opened_file.read()
>>> the_file_content
'Hi there! I am a .txt file!'
The opened_file
is a file descriptor object. In the above example, the read()
method reads the entire content of the file. If you wish, you can read just a portion of the file, as is shown below:
>>> the_file_is = open('file.txt')
>>> the_part_file_is = the_file_is.read(10)
>>> the_part_file_is
'Hi there! '
You could read the data of a file line by line. There is a method that does that. Let’s add few more lines to our file.
Line 1 - Hi there! I am a .txt file!
Line 2 - Hi there! I am a .txt file!
Line 3 - Hi there! I am a .txt file!
Line 4 - Hi there! I am a .txt file!
Line 5 - Hi there! I am a .txt file!
Here is how you can read line by line:
>>> the_file_txt = open('file.txt')
>>> line_one = the_file_txt.readline()
>>> line_one
'Line 1 - Hi there! I am a .txt file!\n'
If you want to read a specific line then you can do so:
>>> lines_list = open('file.txt')
>>> lines_list_read = lines_list.readlines()
>>> line_three = lines_list_read[2]
>>> line_three
'Line 3 - Hi there! I am a .txt file!\n'
Let’s see now how to write (or append) to a text file. You can do it with w
which stands for “writing mode” or with a
which stands for “append mode”. The w
will delete the whole content of the file and will write the new content. The a
just appends the new content (at the end of the existing content).
The file file.txt
contains just a single line of text which is “Hi there! I am a .txt file!”. First we are going to open the file and read its content then we are going to append the text “I can be modified with Python!”.
>>> file = open('file.txt')
>>> content = file.read()
>>> content
'Hi there! I am a .txt file!'
>>> file_append_mode = open('file.txt', 'a')
>>> file_append_mode.write(' I can be modified with Python!')
31
>>> file_append_mode.close()
>>> read_file_again = open('file.txt')
>>> new_content_file = read_file_again.read()
>>> new_content_file
'Hi there! I am a .txt file! I can be modified with Python!'
If you want to write new content to a file then you have to open it in “writing mode” as shown below:
>>> my_file = open('file.txt', 'w')
>>> my_file.write('I am new content')
16
>>> my_file.close()
>>> read_new_content = new_content.read()
>>> read_new_content
'I am new content'
The writing mode deleted the old content of the file and added the new content which is “I am new content”.