When you’re working with Python, reading and writing files are very useful when you need to read data or save data.
The first thing you’ll need to do is recognize the the mode attribute of a filein python here.
mode
r
open in read-only mode, which is the default
rb/r+
w
write-only mode for rewriting the contents of a file, create a new file if it doesn’t exist.
wb/w+/wb+
a
append mode for adding new content to the end of the file, create a new file if it doesn’t exist.
ab/a+/ab+
b
a mode opens it in binary mode, which is used for non-text files (such as image , pdf, sound and video files)
/
+
read & write mode
/
Read & Write & Append
First, let us create a file and write something to it.
The open function opens a file, it returns something called a file object.
1 2 3 4 5
file = open("Tagore.txt", "w") desc = "Tagore's poems New Moon Gathers describes a harmonious world and praises love with its light lines." file.write(desc + "\n\n\tBy plucking her petals you do not gather the beauty of the flower.\n\t摘下花瓣,并不能得到花的美丽。") # 185 file.close()
OR
1 2 3 4
file = open("Tagore.txt", "w") words = ["Tagore's poems New Moon Gathers describes a harmonious world and praises love with its light lines.\n", '\n', '\tBy plucking her petals you do not gather the beauty of the flower.\n', '\t摘下花瓣,并不能得到花的美丽。'] file.writelines(words) file.close()
Then, read that file,
1 2 3 4 5 6
# file = open("Tagore.txt", 'r', encoding='utf-8') ## 'utf-8' codec can't decode byte 0xcf in position 175: invalid continuation byte
Tagore's poems New Moon Gathers describes a harmonious world and praises love with its light lines.
By plucking her petals you do not gather the beauty of the flower. 摘下花瓣,并不能得到花的美丽。
readline: return a single line
readlines: reads all of the text , but much slower and more inefficient
1 2 3 4 5 6 7 8 9 10 11 12
file = open("Tagore.txt", 'r', errors='ignore') print(file.read(10)) # Tagore's p print(file.readline(10)) # oems New M
print(file.readline()) # oon Gathers describes a harmonious world and praises love with its light lines. print(file.readlines()) # ['\n', '\tBy plucking her petals you do not gather the beauty of the flower.\n', '\t摘下花瓣,并不能得到花的美丽。'] file.close()
More simple, much smoother and faster alternative:
1 2
for line in open("Tagore.txt"): print(line, end="")
1 2 3 4
Tagore's poems New Moon Gathers describes a harmonious world and praises love with its light lines.
By plucking her petals you do not gather the beauty of the flower. 摘下花瓣,并不能得到花的美丽。
Adding to Tagore.txt with append()
1 2 3
file = open("Tagore.txt", 'a+') words = ["\n\tI have heard the liquid murmur of the river through the darkness of midnight","\n\t我听见那河水淙淙的流声,在黑漆的午夜里传过来","\n\tI shall become a dream, and through the little opening of your eyelids I shall slip into the depths of your sleep; and when you wake up and look round startled, like a twinkling firefly I shall flit out into the darkness.","\n\t我要变成一个梦儿,从你的眼皮的微缝中,钻到你睡眠的深处。当你醒来吃惊地四望时,我便如闪耀的萤火似地熠熠地向暗中飞去了。"] file.writelines(words)
With: The file is automatically closed at the end of the with statement, even if exceptions occur within it.
1 2 3 4 5
with open("Tagore.txt") as f: print ("filename: ", f.name) print ("filemode: ", f.mode) for line in f.readlines(): print (line.strip()[:25])
1 2 3 4 5 6 7 8 9 10
filename: Tagore.txt filemode: r Tagore's poems New Moon G
By plucking her petals yo 摘下花瓣,并不能得到花的美丽。 I have heard the liquid m 我听见那河水淙淙的流声,在黑漆的午夜里传过来 I shall become a dream, a 我要变成一个梦儿,从你的眼皮的微缝中,钻到你睡眠的
If either the file is incorrect or doesn’t exist, the error FileNotFoundError will be thrown, which needs to then be caught and handled.
If the decoded error, the error LookupError or UnicodeDecodeError will be thrown.
Thoughts
You’ve already seen files used in many of the examples in this page already, but let’s do some more examples and recap to cement our knowledge.
1 2 3 4 5
msg = input("What are your feelings about the Guido van Rossum?:\n") file = open("thoughts.txt", "w") amount_written = file.write(msg) print("Your input has", amount_written, "bytes.\n") file.close()
What are your feelings about the Guido van Rossum?:
I wrote Python
Your input has 14 bytes.
1 2 3 4
file = open("thoughts.txt", "r") print("Now let's see what you wrote:") print(file.read()) file.close()
Now let's see what you wrote:
I wrote Python
Seek
1 2 3 4 5 6 7 8 9 10 11 12
f = open('seek.txt', 'wb+') f.write(b'0123456789abcdefghijklmnopqrstuvwxyz') # 36