Best way to generate random file names in Python

前端 未结 11 2081
囚心锁ツ
囚心锁ツ 2020-12-04 08:48

In Python, what is a good, or the best way to generate some random text to prepend to a file(name) that I\'m saving to a server, just to make sure it does not overwrite. Tha

11条回答
  •  -上瘾入骨i
    2020-12-04 09:22

    a common approach is to add a timestamp as a prefix/suffix to the filename to have some temporal relation to the file. If you need more uniqueness you can still add a random string to this.

    import datetime
    basename = "mylogfile"
    suffix = datetime.datetime.now().strftime("%y%m%d_%H%M%S")
    filename = "_".join([basename, suffix]) # e.g. 'mylogfile_120508_171442'
    

提交回复
热议问题