打开而不创建和写入文件

open with not creating and writing file

我正在学习教程 (Beautiful Soup),但似乎无法打开以创建 .txt 文件,因为我收到此错误: 用 open(f'posts/{index}.txt', 'w+') 作为 f: FileNotFoundError:[Errno 2] 没有这样的文件或目录:'posts/1.txt'。我尝试查找当前问题的不同解决方案 运行 python 3.9。我还需要采取其他步骤来更正此问题吗?

解释器在您当前的工作目录中找不到目录“posts”。如果它存在,则您不在其父目录中。尝试使用完整路径,例如rf'C:\users\myuser\posts\{index}.txt'rf'~/posts/{index}.txt' linux。

或者,如果不存在,请添加以下行:

import os
os.mkdir('posts')

您可以通过这种方式找到您当前的工作目录:

import os
os.path.abspath('.')