SquareLine Studio+STM32 TFT彩屏UI开发实战
2026/9/27 2:53:26
使用open()函数打开文件,语法如下:
file=open("filename.txt","mode")mode参数指定文件打开方式:
"r":只读(默认)。"w":写入(覆盖原有内容)。"a":追加(在文件末尾添加内容)。"x":创建新文件(如果文件已存在则报错)。"b":二进制模式(如"rb"或"wb")。"t":文本模式(默认)。"+":读写模式(如"r+"或"w+")。读取文件的几种方式:
# 读取整个文件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()# 按行读取为列表写入文件使用write()方法:
file.write("Hello, World!\n")使用"w"模式会覆盖原有内容,使用"a"模式会在文件末尾追加。
操作完成后必须关闭文件以释放资源:
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'])Python 的os和pathlib模块可以处理文件路径。
os模块importos# 获取当前工作目录current_dir=os.getcwd()# 拼接路径file_path=os.path.join("folder","file.txt")# 检查文件是否存在ifos.path.exists(file_path):print("File exists")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()# 创建空文件importos os.makedirs("new_folder",exist_ok=True)importos# 删除文件os.remove("file.txt")# 删除空目录os.rmdir("empty_folder")# 删除非空目录(递归删除)importshutil shutil.rmtree("folder")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文件的读写操作,支持字典形式的数据处理。
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数据的序列化与反序列化功能。
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("无权限访问")