Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python open("file", "w+") not creating a nonexistent file

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'

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading