Home > other >  open with not creating and writing file
open with not creating and writing file

Time:03-12

I am following a tutorial (Beautiful Soup) and I can't seem to get open with to create a .txt file as I am getting this error: with open(f'posts/{index}.txt', 'w ') as f: FileNotFoundError: [Errno 2] No such file or directory: 'posts/1.txt'. I tried looking up different solutions to my problem currently running python 3.9. Is there another step I need to correct this issue?

IDE Pycharm

CodePudding user response:

The interpreter isn't finding the directory "posts" in your current working directory. If it exists, you are not in its parent directory. Try using the full path, e.g. rf'C:\users\myuser\posts\{index}.txt' or rf'~/posts/{index}.txt' on linux.

Or, if it doesnt't exist, add these lines:

import os
os.mkdir('posts')

You can find your current working directory this way:

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