– Start
点击此处观看本系列配套视频。
open 函数
我们可以通过 open 函数来读写文件。
例子1
try:
file_name = r'D:\0_Shangbo\Dev\Python\python_work\test.txt'
f = open(file_name) # 以只读方式打开文件
content = f.read() # 一次读取整个文件
print(content)
finally:
f.close() # 文件必须关闭
例子2
file_name = r'D:\0_Shangbo\Dev\Python\python_work\test.txt'
# 使用 with 打开文件,文件会自动关闭
with open(file_name) as f:
for line in f: # 逐行读取
print(line)
例子3
file_name = r'D:\0_Shangbo\Dev\Python\python_work\test.txt'
# 使用 with 打开文件,文件会自动关闭
with open(file_name) as f:
for line in f.readlines(): # 逐行读取
print(line)