TorbenVerdorben
TorbenVerdorben

Reputation: 159

Creating dir in Python does not work (Windows)

I have a problem with my python project. I startedd coding om my mac and later checked it out on my windows computer. The problem now is, that my method to create a file will not work (even so I adjusted it to the new file system).

What i try to do is create a subdirectory(C:\Users\t\Documents\pythonProject\SampleData\2016-10-19_16:03:57) in an existing directory(C:\Users\t\Documents\pythonProject\SampleData)

However when i execute the code i get an expection that says that the sytax of my filename is not right...

   def create_dir_if_not_exists():
       try:
           ts = time.time()
           st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d_%H:%M:%S')
           Utils.folderTimerStamp = os.path.join('Users', 't', 'Documents', 'pythonProject', 'SampleData')
           Utils.folderName = 'SampleData\\' +st +'\\'

           if not os.path.exists(Utils.folderTimerStamp+"\\" +st  +"\\"):
               os.makedirs(Utils.folderTimerStamp+"\\" +st  +"\\")

       except OSError as exception:
           if exception.errno != errno.EEXIST:
               raise

Upvotes: 1

Views: 357

Answers (3)

MarianD
MarianD

Reputation: 14141

Use the drive letter C: and a backslash as your first parameter in your os.path.join() call:

os.path.join('C:\\','Users', 't', 'Documents', 'pythonProject', 'SampleData')

Upvotes: 1

Łukasz Rogalski
Łukasz Rogalski

Reputation: 23223

You are trying to create file name, which is invalid accoring to NTFS requirements.

Exceprt from docs (emphasis mine):

Use any character in the current code page for a name, including Unicode characters and characters in the extended character set (128–255), except for the following:

  • < (less than)
  • > (greater than)
  • : (colon)
  • " (double quote)
  • / (forward slash)
  • \ (backslash)
  • | (vertical bar or pipe)
  • ? (question mark)

You need to change st value to represent valid NTFS filename, e.g.

st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d_%H-%M-%S')

Upvotes: 1

R__raki__
R__raki__

Reputation: 975

In windows

Folder names or filenames cannot contain any of these \/:*?"<>| characters.

So replace : any other character other than above

I have replaced : to -

strftime('%Y-%m-%d_%H-%M-%S')

Upvotes: 1

Related Questions