SuitUp
SuitUp

Reputation: 3182

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?

Upvotes: 0

Views: 388

Answers (1)

mattbornski
mattbornski

Reputation: 12553

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!')

Upvotes: 4

Related Questions