目录
文本文件 VS. 二进制文件
文件处理的步骤: 打开 - 操作 - 关闭

file_object = open("filename", "openmode")
... #操作
file_object.close()
with open("filename", "openmode") as file_object:
... #操作
filename:文件路径及名称,当与源文件同目录是可省略路径openmode:打开模式,文本or二进制,读or写| openmode | details |
|---|---|
| ‘r‘ | 只读模式,默认值,如果文件不存在,返回FileNotFoundError |
| ‘w‘ | 覆盖写模式,文件不存在则创建,存在则完全覆盖 |
| ‘x‘ | 创建写模式,文件不存在则创建,存在则返回FileExistsError |
| ‘a‘ | 追加写模式,文件不存在则创建,存在则在文件最后追加内容 |
| ‘b‘ | 二进制文件模式 |
| ‘t‘ | 文本文件模式,默认值 |
| ‘+‘ | 与r/w/x/a一同使用,在原功能基础上增加同时读写功能 |
| operation | details |
|---|---|
| f.read(size=-1) | 读入全部内容,如果给出参数,读入前size长度 |
| f.readline(size=-1) | 读入一行内容,如果给出参数,读入该行前size长度 |
| f.readlines(hint=-1) | 读入文件所有行,以每行为元素形成列表,如果给出参数,读入前hint行 |
| f.write(s) | 向文件写入一个字符串或字节流 |
| f.writelines(lines) | 将一个元素全为字符串的列表写入文件 |
| f.seek(offset) | 改变当前文件操作指针的位置,offset含义如下:0 – 文件开头; 1 – 当前位置; 2 – 文件结尾 |
一次读入,统一处理
fo = open(fname,"r")
txt = fo.read()
...#对全文txt进行处理
fo.close()
按数量读入,逐步处理
fo = open(fname,"r")
txt = fo.read(2)
while txt != "":
#对txt进行处理
txt = fo.read(2)
fo.close()
一次读入,分行处理
fo = open(fname,"r")
for line in fo.readlines():
print(line)
fo.close()
分行读入,逐行处理
fo = open(fname,"r")
for line in fo:
print(line)
fo.close()
fo = open("output.txt","w+")
ls = ["China", "France", "America"]
fo.writelines(ls)
fo.seek(0)
for line in fo:
print(line)
fo.close()原文:https://www.cnblogs.com/tzhao/p/9855232.html