2

The problem is: I have to create a file in an automatically way into some folder which have been automatically created before.

Let me explain better. First I post the code used to create the folder...

import os
from datetime import datetime

timestr = datetime.now().strftime("%Y%m%d-%H%M%S-%f")

now = datetime.now()
newDirName = now.strftime("%Y%m%d-%H%M%S-%f")
folder = os.mkdir('C:\\Users\\User\\Desktop\\' + newDirName)

This code will create a folder on Desktop with timestamp (microseconds included to make it as unique as possible..) as name.

Now I would like to create also a file (for example a txt) inside the folder. I already have the code to do it...

file = open('B' + timestr, 'w')
file.write('Exact time is: ' + timestr)
file.close()

How can I "combine" this together ? First create the folder and, near immediately, the file inside it?

Thank you. If it's still not clear, feel free to ask.

1 Answer 1

3

Yes, just create a directory and then immediately a file inside it. All I/O operations in Python are synchronous by default so you won't get any race conditions.

Resulting code will be (also made some improvings to your code):

import os
from datetime import datetime

timestr = datetime.now().strftime("%Y%m%d-%H%M%S-%f")
dir_path = os.path.join('C:\\Users\\User\\Desktop', timestr)
folder = os.mkdir(dir_path)

with open(os.path.join(dir_path, 'B' + timestr), 'w') as file:
    file.write('Exact time is: ' + timestr)

You can also make your code (almost) cross-platform by replacing hard-coded desktop directory path with

os.path.join(os.path.expanduser('~'), 'Desktop')
Sign up to request clarification or add additional context in comments.

1 Comment

Added some improvements

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.