文件操作的模式
文件操作的模式如下表:
模式 | 文件存在 | 文件不存在 | 操作 | 文件内容 | 如果文件不存在 | 是否覆盖 |
r read | 创建open对象正常,正常打开 | 创建open对象报错,无法读取原文件 | 只读 | 只可读不可写, 默认就是r模式。 可以用指针调节位置去读。 | 报错 | - |
w write | 创建open对象正常,原文件内容直接清空 | 创建open对象正常,创建新文件 | 只写 | 打开文件时,内容就被清空。可以调节指针位置去写。 | 创建 | 覆盖 |
a append | 创建open对象正常,正常打开 | 创建open对象正常,创建新文件 | 追加 | 不覆盖原文件内容。只能在末尾追加内容,调节指针无法改变写的位置。如果不写内容,原文件不变。 | 创建 | 否,追加写 |
r+ | 创建open对象正常,正常打开 | 创建open对象报错,无法读取原文件 | 读写 | 不覆盖原文件内容。指针默认在末尾追加内容,指针在其它位置写操作时,覆盖原文件内容。如果不写内容,原文件不变。根据指针位置读文件。 | 报错 | 覆盖 |
w+ | 创建open对象正常,原文件内容直接清空 | 创建open对象正常,创建新文件 | 读写 | 打开文件时,内容就被清空。写操作覆盖之前的文件内容。根据指针位置读文件。 | 创建 | 覆盖 |
a+ | 创建open对象正常,正常打开 | 创建open对象正常,创建新文件 | 读写 | 文件指针默认在末尾,写文件只能追加内容,根据指针位置读文件。如果不写内容,原文件不变。 | 创建 | 否,追加写 |
备注:只要是可写模式,在关闭文件之前,都可以多次调用write方法追加内容 |
1. open 打开文件
使用 open 打开文件后一定要记得调用文件对象的 close() 方法。比如可以用 try/finally 语句来确保最后能关闭文件。
file_object = open(r'D:\test.txt') # 打开文件
try:
all_the_text = file_object.read( ) # 读文件的全部内容
finally:
file_object.close( ) # 关闭文件
print(all_the_text)
注:不能把 open 语句放在 try 块里,因为当打开文件出现异常时,文件对象 file_object 无法执行 close() 方法。
2. 读文件
读文本文件方式打开文件
file_object = open(r'D:\test.txt', 'r') # 打开文件
#第二个参数默认为 r
file_object = open(r'D:\test.txt') # 打开文件
读二进制文件方式打开文件
file_object= open(r'D:\test.txt', 'rb') # 打开文件
读取所有内容
file_object = open(r'D:\test.txt') # 打开文件
try:
all_the_text = file_object.read( )# 读文件的全部内容
finally:
file_object.close( ) # 关闭文件
print(all_the_text)
读固定字节
file_object = open(r'D:\test.txt', 'rb') # 打开文件
try:
while True:
chunk = file_object.read(100) # 读文件的100字节
if not chunk:
break
#do_something_with(chunk)
finally:
file_object.close( ) # 关闭文件
读全部行 readlines
file_object = open(r'D:\test.txt', 'r') # 打开文件
list_of_all_the_lines = file_object.readlines( ) #读取全部行(从文件指针位置开始读取全部行,读取之后返回一个列表,每行作为列表的一个元素)
print(list_of_all_the_lines)
file_object.close( ) # 关闭文件
如果文件是文本文件,还可以直接遍历文件对象获取每行:
file_object = open(r'D:\test.txt', 'r') # 打开文件
for line in file_object:
print(line)
file_object.close( ) # 关闭文件
readline() 从文件中读取一行内容(line by line),并以此作为一个 字符串返回; 从文件指针位置开始,执行一次读取一行
readlines() 将文件中的每行内容作为一个字符串存入列表中,并返回该列表 (all lines) ;从文件指针位置开始,执行一次读取全部行
3. 写文件
写文本文件方式打开文件
file_object= open('data', 'w')
写二进制文件方式打开文件
file_object= open('data', 'wb')
追加写文件方式打开文件
file_object= open('data', 'w+')
写数据
all_the_text="aaa\nbbb\nccc\n"
file_object = open(r'D:\thefile.txt', 'w') # 打开文件
file_object.write(all_the_text) #写入数据
file_object.close( ) # 关闭文件
写入多行
all_the_text="aaa\nbbb\nccc\n"
file_object = open(r'D:\thefile.txt', 'w')# 打开文件
file_object.writelines(all_the_text) #写入数据
file_object.close( ) # 关闭文件
追加
file = r'D:\thefile.txt'
with open(file, 'a+') as f: # 打开文件
f.write('aaaaaaaaaa\n')
判断文件是否存在:
import os.path
if os.path.isfile("D:\\test.txt"): # 判断文件是否存在
print(":\\test.txt exists")
import os
os.getcwd() # 获得当前目录,获得当前工作文件夹,工作目录
os.chdir("D:\\test.txt") # 改变当前目录,获得当前工作文件夹,
REF
https://www.runoob.com/python3/python3-file-methods.html