python 文件操作
读文件
f = open("/usr/demo/data.txt","r") # 文件不存在会报错
print(f.read())
读一行
f = open("/usr/demo/data.txt","r")
print(f.readline())
文件自动关闭
with open("/usr/demo/data.txt","r") as f:
print(f.read())
写文件
写入模式
with open("./1.txt", "w") as f: # 文件不存在会创建文件
f.write("Hello")
f.write("World!")
附加内容
with open("./1.txt", "a") as f: # 文件不存在会创建文件
f.write("Hello")
f.write("World!")
同时读写文件
with open("./1.txt", "r+") as f: # 写入会追加到文件
f.write("Hello")
f.write("World!")