Search code examples
pythonmacosfilefile-iowith-statement

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'

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.