Skip to content

读写文件

常用模式

模式可做操作若文件不存在是否覆盖文件原来内容
r只读报错——
r+可读、可写报错
w只写创建
w+可读、可写创建
a只写创建否,追加写
a+可读、可写创建否,追加写

打开文件

直接打开

python
f = open(filename, 'r+', encoding='utf-8')

使用with语句打开

使用 with 关键字。优点是当子句体结束后文件会正确关闭,即使在某个时刻引发了异常。

python
with  open('sample3.txt','w') as f:
    f.write('hello,my friends!\nthis is python big data analysis')
f.close()

读取文件

逐行读取文本文件

python
for line in open("foo.txt"):
    print line

或者

python
line = f.readline()               # 调用文件的 readline()方法  
while line:  
    print line,                   # 后面跟 ',' 将忽略换行符  
    #print(line, end = '')       # 在 Python 3 中使用  
    line = f.readline()

读取全部内容

python
all_the_text = file_object.read()

写入文件

.write() 方法用于在文本文件中写入并添加你想要的字符串内容。

python
with open("text.txt","w") as file:
    file.write("I am learning Python!\n")
    file.write("I am really enjoying it!\n")
    file.write("And I want to add more lines to say how much I like it")

关闭文件

python
f.close()

参考文献

  1. 内置函数 — Python 3.11.0 文档