Python在已有文件夹创建文件遇FileNotFoundError求助
问题解决方法
你的问题核心是f-string中的反斜杠被当作转义字符解析,导致路径异常,同时要确保路径解析符合Python的文件系统规则。以下是几种可行的修复方案:
方案1:使用正斜杠替代反斜杠
Python在文件路径中支持跨平台的正斜杠,完全不需要依赖Windows的反斜杠,直接修改路径拼接方式:
content = ["eat", "drink","sleep"] filenames = ["todo1.txt","todo2.txt","todo3.txt"] for stuff, filename in zip(content, filenames): # 用正斜杠拼接路径 with open(f"files/{filename}", "w") as file: file.write(stuff)
注意:这里改用
with语句,会自动关闭文件,比手动调用file.close()更安全。
方案2:使用原始f-string
在f-string前加r前缀,让Python将字符串视为原始字符串,反斜杠不会被解析为转义字符:
content = ["eat", "drink","sleep"] filenames = ["todo1.txt","todo2.txt","todo3.txt"] for stuff, filename in zip(content, filenames): with open(rf"files\{filename}", "w") as file: file.write(stuff)
方案3:使用os.path模块拼接路径(推荐)
用Python内置的路径处理模块,自动适配不同操作系统的路径规则,避免手动拼接的错误:
import os content = ["eat", "drink","sleep"] filenames = ["todo1.txt","todo2.txt","todo3.txt"] for stuff, filename in zip(content, filenames): file_path = os.path.join("files", filename) with open(file_path, "w") as file: file.write(stuff)
额外检查点
- 确认
files文件夹确实存在于当前脚本的工作目录下(可以用print(os.getcwd())查看当前工作路径) - 若
files在其他路径,需使用绝对路径拼接,比如os.path.join("C:/your/path/to/files", filename)
内容的提问来源于stack exchange,提问作者Ved Verma
相关产品推荐
相关产品推荐

