Skip to main content

文件

文件

写文件

我们使用 open 函数的写入模式来写文件:

f = open('test.txt', 'w')
f.write('hello world.')
f.close()
print(open('test.txt').read())

使用 w 模式时,如果文件不存在会被创建

除了写入模式,还有追加模式 a

读写模式w+

f = open('test.txt', 'w+')
f.write('hello world. morning.')
f.seek(3)
print(f.read()) # hello world.
f.close()

读文件

使用 open 函数 来读文件,使用文件名的字符串作为输入参数:

默认打开文件是 ‘r’ 读模式

f = open("test.txt")

# 默认以读的方式打开文件,如果文件不存在会报错。
# 可以使用 read 方法来读入文件中的所有内容:
text = f.read()
print(text)

按照行读入内容,readlines 方法返回一个列表,每个元素代表文件中每一行的内容:

f = open("test.txt")
lines = f.readlines()
print(lines)
f.close()
# 事实上,我们可以将 f 放在一个循环中,得到它每一行的内容:
f = open('test.txt')
for line in f:
print(line)
f.close()

上下文管理器

with open('my_file.txt', 'w') as fp:
data = fp.write("Hello world")

这等效于下面的代码,但是要更简便:

fp = open('my_file.txt', 'w')
try:
# do stuff with f
data = fp.write("Hello world")
finally:
fp.close()

自定义上下文管理器

比如可以这样定义一个简单的上下文管理器:

class ContextManager(object):
def __enter__(self):
print("Entering")

def __exit__(self, exc_type, exc_value, traceback):
print("Exiting")


with ContextManager():
print("inside operate")

enter 的返回值

如果在 enter 方法下添加了返回值,

那么我们可以使用 as 把这个返回值传给某个参数:

class ContextManager2(object):
def __enter__(self):
print("Entering")
return "my value"

def __exit__(self, exc_type, exc_value, traceback):
print("Exiting")


with ContextManager2() as val:
print(val)

一个通常的做法是将 enter 的返回值设为这个上下文管理器对象本身, 文件对象就是这样做的.

class ContextManager3(object):
def __enter__(self):
print("Entering")
return self

def __exit__(self, exc_type, exc_value, traceback):
print("Exiting")

错误处理

上下文管理器对象将错误处理交给 exit 进行,可以将错误类型, 错误值和 traceback 等内容作为参数传递给 exit 函数:

class ContextManager4(object):
def __enter__(self):
print("Entering")

def __exit__(self, exc_type, exc_value, traceback):
print("Exiting")
if exc_type is not None:
print(" Exception:", exc_value)
return True # 不想让错误抛出,只需要将 __exit__ 的返回值设为 True


with ContextManager4():
print(1 / 0)

import os
os.remove('my_file.txt')

二进制文件

二进制读写模式 b:

import os

f = open('binary.bin', 'wb')
f.write(os.urandom(10))
f.close()
f = open('binary.bin', 'rb')
print(repr(f.read()))
f.close()

with 方法

事实上,Python提供了更安全的方法,当 with 块的内容结束后, Python会自动调用它的close 方法,确保读写的安全:

with open('new_file.txt', 'w') as f:
for i in range(3000):
x = 1.0 / (i - 1000)
f.write('hello world: ' + str(i) + '\n')

与 try/exception/finally 效果相同,但更简单。

查看文件写的结果,虽然触发error,但已经写的内容是成功的。

!tail new_file.txt
!wc -l new_file.txt
# 删除文件:
import os
os.remove('test.txt')
os.remove('binary.bin')
os.remove('new_file.txt')