当输出文件存在于路径中时创建输出文件

发布于 2024-12-01 21:43:43 字数 85 浏览 8 评论 0原文

如何在 python 中编写当输出文件存在于路径中时,输出文件将自动为“originalname”+“_1”/“originalname”+“_2”等选项?

How do I code in python the option that when the output file exists in the path, the output file will automatically be "originalname"+"_1" / "originalname"+"_2" and so on ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

最初的梦 2024-12-08 21:43:43

类似的内容,

import os.path

def getnewfilename(filename):
    testfile = filename
    i = 0
    while os.path.exists(testfile):
        i += 1
        testfile = "%s_%s" % (testfile, i) 

    return testfile

应该会生成

filename
filename_1
filename_2

如果您使用 %s_%3i"

filename
filename_001
filename_002
filename_003

然后您应该得到它,然后按字母顺序列出(但当 i>=1000 时会出现问题)

Something like

import os.path

def getnewfilename(filename):
    testfile = filename
    i = 0
    while os.path.exists(testfile):
        i += 1
        testfile = "%s_%s" % (testfile, i) 

    return testfile

This should generate

filename
filename_1
filename_2

if you use %s_%3i" you should get

filename
filename_001
filename_002
filename_003

which will then list alphabetically (but have problems when i>=1000)

幽梦紫曦~ 2024-12-08 21:43:43

您可以使用 os.path.exists检查文件是否已存在。剩下的就是一个尝试新文件名的简单循环。

You can use os.path.exists to check if a file already exists. The rest is a simple loop that tries new filenames.

别在捏我脸啦 2024-12-08 21:43:43

isfile 检查文件是否存在并也进入 simlinks;您可以使用完整的文件路径。

if os.path.isfile(filename):
    do_something()

isfile checks for the existence of a file and goes down simlinks as well; you can use the full filepath.

if os.path.isfile(filename):
    do_something()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文