file_handle = open('/home/hsj/Files/data.txt', mode='a+')
try:
file_handle.write(str(value)) #value是我们想要写入的数据
file_handle.write('\n') #因为不会自动换行,手动写入一行
except:
file_handle.close()
2、Python如何读文件
推荐一行一行的读,因为如果一下全部读完可能会出现爆内存的情况
read_file = "/home/hsj/Files/data.txt"
with open(read_file, 'r', encoding="utf-8") as f:
while True:
str_data = f.readline()
str_data = str_data.strip('\n')
if str_data:
print(str_data)
else:
break