【python笔记】文件读写


open函数的打开基本模式

  • r:只读模式。从文件开头读。操作的文件必须存在
  • w:只写模式。若文件存在则清空,不存在则创建
  • a:追加模式。只写权限。追加内容到文件末尾。文件不存在则创建

读写二进制格式的文件一般用rbwb等。

读文件

  • 简单的读文件
with open("test.md","r",encoding="utf-8") as fobj:
    print(fobj.read())
  • for循环读取
with open("test.md","r",encoding="utf-8") as fobj:
    for i in fobj.readlines():
        print(f"content is: {i}")
  • 取消readlines内的换行符
with open("test.py","r",encoding="utf-8") as fobj:
    for i in fobj.read().splitlines():
        print(f"content is: {i}")

写文件

with open("hello.txt","a",encoding="utf-8") as f_obj:
    f_obj.write("hello,world!")

write()writelines()都不会自动换行
写在for循环内:

for i in range(1,10):
    with open("hello.txt","a",encoding="utf-8") as f_obj:
    	f_obj.write(f"\nPage: {i}, hello, world!")