Search code examples
pythonfilebuilt-in

Why pythons open function throw exception if file not exist only when i use os.sep inside filename?


This works fine:

file1 = open("not_exisiting_file1.txt", "w")

but this not:

file2 = open("folder" + os.sep + "not_exisiting_file2.txt", "w")

Why?


Solution

  • The most likely answer I can imagine without knowing more about your situation is that the folder "folder" does not exist. This has nothing to do with os.sep.

    Try this:

    import os, os.path
    folder = 'folder'
    os.makedirs(folder)
    with open(os.path.join(folder, 'file1.txt'), 'w') as f:
      f.write('now my folder and file both exist!')