Python文件操作
- 一、文件读取
- 1、打开文件
- 2、读取文件内容
- 二、文件写入
- 1、写入文件
- 2、关闭文件
- 三、文件路径处理
- 1、文件路径处理
- (1)、使用 `os` 模块
- (2)、使用 `pathlib` 模块(Python 3.4+)
- 2、目录操作
- (1)、创建目录
- (2)、删除文件或目录
- (3)、遍历目录
- 四、二进制文件操作
- 五、CSV文件处理
- 六、JSON文件处理
- 七、文件压缩与解压
- 八、异常处理
一、文件读取
1、打开文件
使用open()函数打开文件,语法如下:
file=open("filename.txt","mode")mode参数指定文件打开方式:
"r":只读(默认)。"w":写入(覆盖原有内容)。"a":追加(在文件末尾添加内容)。"x":创建新文件(如果文件已存在则报错)。"b":二进制模式(如"rb"或"wb")。"t":文本模式(默认)。"+":读写模式(如"r+"或"w+")。
2、读取文件内容
读取文件的几种方式:
# 读取整个文件content=file.read()# 逐行读取lines=file.readlines()# 逐行迭代forlineinfile:print(line.strip())# 基础读取方式file=open('example.txt','r')content=file.read()file.close()# 推荐使用with语句withopen('example.txt')asf:lines=f.readlines()# 按行读取为列表二、文件写入
1、写入文件
写入文件使用write()方法:
file.write("Hello, World!\n")使用"w"模式会覆盖原有内容,使用"a"模式会在文件末尾追加。
2、关闭文件
操作完成后必须关闭文件以释放资源:
file.close()为避免忘记关闭文件,推荐使用with语句:
withopen("filename.txt","r")asfile:content=file.read()# 覆盖写入withopen('output.txt','w')asf:f.write('Hello, World!\n')# 追加写入withopen('output.txt','a')asf:f.writelines(['Line 1\n','Line 2\n'])三、文件路径处理
1、文件路径处理
Python 的os和pathlib模块可以处理文件路径。
(1)、使用os模块
importos# 获取当前工作目录current_dir=os.getcwd()# 拼接路径file_path=os.path.join("folder","file.txt")# 检查文件是否存在ifos.path.exists(file_path):print("File exists")(2)、使用pathlib模块(Python 3.4+)
frompathlibimportPath# 创建路径对象file_path=Path("folder")/"file.txt"# 读取文件内容content=file_path.read_text()# 写入文件file_path.write_text("New content")importosfrompathlibimportPath# 使用os.pathdir_path=os.path.dirname('/path/to/file.txt')exists=os.path.exists('file.txt')# 使用pathlibpath=Path('data/file.txt')parent_dir=path.parent path.touch()# 创建空文件2、目录操作
(1)、创建目录
importos os.makedirs("new_folder",exist_ok=True)(2)、删除文件或目录
importos# 删除文件os.remove("file.txt")# 删除空目录os.rmdir("empty_folder")# 删除非空目录(递归删除)importshutil shutil.rmtree("folder")(3)、遍历目录
importosforroot,dirs,filesinos.walk("folder"):forfileinfiles:print(os.path.join(root,file))四、二进制文件操作
处理图片、视频等非文本文件时,需使用'rb'或'wb'模式进行二进制读写。
# 复制图片文件withopen('input.jpg','rb')assrc,open('copy.jpg','wb')asdst:dst.write(src.read())# 读取二进制文件withopen("image.jpg","rb")asfile:data=file.read()# 写入二进制文件withopen("copy.jpg","wb")asfile:file.write(data)五、CSV文件处理
csv模块简化CSV文件的读写操作,支持字典形式的数据处理。
importcsv# 写入CSVwithopen('data.csv','w',newline='')asf:writer=csv.writer(f)writer.writerow(['Name','Age'])writer.writerow(['Alice',25])# 读取CSV为字典withopen('data.csv','r')asf:reader=csv.DictReader(f)forrowinreader:print(row['Name'],row['Age'])六、JSON文件处理
json模块提供JSON数据的序列化与反序列化功能。
importjson data={'name':'Bob','score':90}# 写入JSON文件withopen('data.json','w')asf:json.dump(data,f,indent=2)# 读取JSON文件withopen('data.json')asf:loaded=json.load(f)print(loaded['name'])七、文件压缩与解压
使用zipfile模块
importzipfile# 创建 ZIP 文件withzipfile.ZipFile("archive.zip","w")aszipf:zipf.write("file1.txt")zipf.write("file2.txt")# 解压 ZIP 文件withzipfile.ZipFile("archive.zip","r")aszipf:zipf.extractall("extracted_folder")八、异常处理
文件操作需处理IOError或FileNotFoundError等异常。
try:withopen('missing.txt')asf:content=f.read()exceptFileNotFoundError:print("文件不存在")exceptPermissionError:print("无权限访问")