Is this the best way to get unique version of filename w/ Python?

前端 未结 6 821
情话喂你
情话喂你 2021-02-05 12:36

Still \'diving in\' to Python, and want to make sure I\'m not overlooking something. I wrote a script that extracts files from several zip files, and saves the extracted files t

6条回答
  •  温柔的废话
    2021-02-05 13:06

    Yes, this is a good strategy for readable but unique filenames.

    One important change: You should replace os.path.isfile with os.path.lexists! As it is written right now, if there is a directory named /foo/bar.baz, your program will try to overwrite that with the new file (which won't work)... since isfile only checks for files and not directories. lexists checks for directories, symlinks, etc... basically if there's any reason that filename could not be created.

    EDIT: @Brian gave a better answer, which is more secure and robust in terms of race conditions.

提交回复
热议问题