0
with open(r"path/sample.txt")as file:
    some operations 
    print('exiting')

when i open the file is it possible to open the filename as below
sample2018-10-25-18-25-36669_devicename_uuid

How to create filenames in python with UTCdatetime & Hostname and guid, for example i need the below mentioned format of file

I am already opening a file to perform some string operations and store it in the same file. It could be very great if I can create a filename while starting the open operation or can I create a file and do all the operations and rename the file in the above mentioned format. How to proceed with this further. I am very new to python

Carlos
  • 5,991
  • 6
  • 43
  • 82
Helen
  • 69
  • 1
  • 8
  • Do you want random uuid? – Olvin Roght Aug 20 '20 at 13:59
  • `'_'.join((datetime.now().strftime('sample%Y-%m-%d-%H-%M-%S-%f'), 'devicename', str(uuid4()))) + '.txt'`. Docs: [`datetime`](https://docs.python.org/3/library/datetime.html#datetime-objects), [`uuid`](https://docs.python.org/3/library/uuid.html). – Olvin Roght Aug 20 '20 at 14:11

1 Answers1

0

Sure, you can generate a filename in python dynamically. There is a simple code example that would help you generate file name as you describe.

import os
import socket
from datetime import datetime
from uuid import uuid4
dt = datetime.utcnow().strftime("%Y-%m-%d-%H-%M-%s")
path = 'path'
hostname = socket.gethostname()
filename = f"samle{dt}-{hostname}-{uuid4()}"
with open(os.path.join(path, filename), 'w') as f:
    f.write('some_content')

If you want to get a unique hardware ID with Python please check this link