[Python] Trying to use open(filename, 'w' ) gives IOError: [Errno 2] No such file or directory...

Discussão em 'Python' iniciado por Stack, Agosto 4, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to create and write to a text file using Python, like so:

    afile = 'D:\\temp\\test.txt'
    outFile = open(afile, 'w' )
    outFile.write('Test.')
    outFile.close()


    But I get an error like:

    Error: 2
    Traceback (most recent call last):
    File "<maya console>", line 1, in <module>
    IOError: [Errno 2] No such file or directory: 'D:\\temp\\test.txt'


    When I tried to look for a solution, most answers I found related to the slashes in the path. But I still got errors if I tried using 'D:/temp/test.txt', or r'D:\temp\test.txt' as the path.

    I can, however, create a file at the root of the drive: the filenames 'D:/test.txt', 'D:\\test.txt' and r'D:\test.txt' all work.

    It seems that I can't create the directory path I would like while trying to create the file.

    How should I create a file at a specific path in Python? Does open() create directories if they don't exist, or do I need to explicitly create the directory path first?

    Continue reading...

Compartilhe esta Página