file operation
f = open("./data.txt", "r", encoding="utf-8")
print(f.read())
print(f.read()) # f.read() will return a null string, because the first read get the pointer to the file end
f.close()
f = open("./data.txt", "r", encoding="utf-8")
print(f.readline()) # read one line content
print(f.readline())
f.close()
f = open("./data.txt", "r", encoding="utf-8")
print(f.readlines()) # read the file contents to shown as a list
f.close()
with open("./data.txt", "r", encoding="utf-8") as f:
lines = f.readlines()
for line in lines:
print(line)
# not need a close operation
# w mode will erase the previous contents
f = open("poem.txt", "w", encoding="utf-8")
f.write("我欲乘风归去,\n又恐琼楼玉宇,\n高处不胜寒。\n")
f.close()
# a mode will append new context at the eof
f = open("poem.txt", "a", encoding="utf-8")
f.write("qi\n")
f.write("hao")
f.close()