Similar questions exist on Stack Overflow. I have read such questions and they have not resolved my problem. The simple code below results in a File Not Found Error. I am running Python 3.9.1 on Mac OS X 11.4
Can anyone suggest next steps for troubleshooting the cause of this?
with open("/Users/root/test/test.txt", "w ") as f:
f.write("test")
Traceback (most recent call last):
File "/Users/root1/PycharmProjects/web_crawler/test.py", line 1, in <module>
with open("/Users/root/test/test.txt", "w ") as f:
FileNotFoundError: [Errno 2] No such file or directory: '/Users/root/test/test.txt'
CodePudding user response:
You comments on initial post clarify what you need to happen.
Below assumes that
- The directory
Users/root1/
exists - You are trying to create a new sub directory file inside it
import os
# Wrap this in a loop if you need
new_dir = 'test' # The variable directory name
new_path = 'Users/root1/' new_dir "/"
os.makedirs(os.path.dirname(new_path), exist_ok=True) # Create new dir 'Users/root1/${new_dir}/
with open(new_path "test.txt", "w ") as f:
# Create new file in afore created directory
f.write("test")
This creates a new directory based on a variable new_dir
and creates the file test.txt
in it.
CodePudding user response:
**sometimes the compiler can't find any path like that you insert in open() function. at that time as possible you can save by default in the folder where your programs were saved by IDE. the followed syntax may be helpful for you **
with open('test.txt', 'w ') as f:
f.write("xyz")
**here the text.txt will save default in the folder where your IDE stores the program that you write. you can check that folder for conformation **