我在 Windows 上使用 PyCharm,但无法在文件夹中创建 3 个文件。我听了两遍这个讲座,还有上一个讲座,但我找不到解决我的问题的方法。
这是我现在的代码:
`contents = ["All carrots are to be sliced longitudinally.", "The carrots were perfectly sliced.", "The carrots were reportedly sliced."]
filenames = ["doc.txt", "report.txt", "presentation.txt"]
for content, filename in zip(contents, filenames):
file = open(f"../files/{filename}", 'w')
file.write(content)`
无论我尝试什么,我都会遇到同样的错误:
file = open(f"../files/{filename}", 'w')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: '../files/doc.txt'
我不确定如何修复此错误,我需要有关此问题的帮助。
我已经尝试过讲座中编写的代码:
for content, filename in zip(contents, filenames):
file = open(f"../files/{filename}", 'w')
file.write(content)
没成功。
我还浏览了讲座中提出的问题并使用了其中 1 个示例:
for content, filename in zip(contents, filenames):
file_path = os.path.join("files", filename)
file = open(file_path, 'w')
file.write(content)
但这也不起作用。
我期待代码创建 3 个文件
["doc.txt", "report.txt", "presentation.txt"]
并按顺序将每个字符串保存在文件中 ["All carrots are to be sliced longitudinally.", "The carrots were perfectly sliced.", "The carrots were reportedly sliced."]
。例如,"All carrots are to be sliced longitudinally."
将保存在 "doc.txt"
中,其他字符串依此类推。