汉狮做网站公司郑州,新手如何学代码,jpress 和wordpress,杭州网站建设服务Python文件操作一、文件读取 1、打开文件2、读取文件内容二、文件写入 1、写入文件2、关闭文件三、文件路径处理 1、文件路径处理 #xff08;1#xff09;、使用 os 模块 #xff08;2#xff09;、使用 pathlib 模块#xff08;Python 3.4#xff09;2、目录操作 …Python文件操作一、文件读取1、打开文件2、读取文件内容二、文件写入1、写入文件2、关闭文件三、文件路径处理1、文件路径处理1、使用 os 模块2、使用 pathlib 模块Python 3.42、目录操作1、创建目录2、删除文件或目录3、遍历目录四、二进制文件操作五、CSV文件处理六、JSON文件处理七、文件压缩与解压八、异常处理一、文件读取1、打开文件使用open()函数打开文件语法如下fileopen(filename.txt,mode)mode参数指定文件打开方式r只读默认。w写入覆盖原有内容。a追加在文件末尾添加内容。x创建新文件如果文件已存在则报错。b二进制模式如rb或wb。t文本模式默认。读写模式如r或w。2、读取文件内容读取文件的几种方式# 读取整个文件contentfile.read()# 逐行读取linesfile.readlines()# 逐行迭代forlineinfile:print(line.strip())# 基础读取方式fileopen(example.txt,r)contentfile.read()file.close()# 推荐使用with语句withopen(example.txt)asf:linesf.readlines()# 按行读取为列表二、文件写入1、写入文件写入文件使用write()方法file.write(Hello, World!\n)使用w模式会覆盖原有内容使用a模式会在文件末尾追加。2、关闭文件操作完成后必须关闭文件以释放资源file.close()为避免忘记关闭文件推荐使用with语句withopen(filename.txt,r)asfile:contentfile.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_diros.getcwd()# 拼接路径file_pathos.path.join(folder,file.txt)# 检查文件是否存在ifos.path.exists(file_path):print(File exists)2、使用pathlib模块Python 3.4frompathlibimportPath# 创建路径对象file_pathPath(folder)/file.txt# 读取文件内容contentfile_path.read_text()# 写入文件file_path.write_text(New content)importosfrompathlibimportPath# 使用os.pathdir_pathos.path.dirname(/path/to/file.txt)existsos.path.exists(file.txt)# 使用pathlibpathPath(data/file.txt)parent_dirpath.parent path.touch()# 创建空文件2、目录操作1、创建目录importos os.makedirs(new_folder,exist_okTrue)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:datafile.read()# 写入二进制文件withopen(copy.jpg,wb)asfile:file.write(data)五、CSV文件处理csv模块简化CSV文件的读写操作支持字典形式的数据处理。importcsv# 写入CSVwithopen(data.csv,w,newline)asf:writercsv.writer(f)writer.writerow([Name,Age])writer.writerow([Alice,25])# 读取CSV为字典withopen(data.csv,r)asf:readercsv.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,indent2)# 读取JSON文件withopen(data.json)asf:loadedjson.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:contentf.read()exceptFileNotFoundError:print(文件不存在)exceptPermissionError:print(无权限访问)