gpt4 book ai didi

python - 这个应该重命名文件的python代码有什么问题?

转载 作者:太空宇宙 更新时间:2023-11-04 09:17:29 26 4
gpt4 key购买 nike

这段代码是为了请求一个目录,然后列出该目录中的所有文件,然后重命名到它们在该列表中的位置,问题是我总是得到错误 2,找不到文件,而如果我打印列表它显然确实找到了文件,因为列表不是空白的。

import os, sys    
path = input("input path: ")
dirs = os.listdir(path)
for i in range(0,len(dirs)):
os.rename(dirs[i], str(i))

给定输入文件,我想用数字重命名基本文件名,但保留文件扩展名。因此

输入'a.txt', 'test.txt', 'test1.txt'

输出'0.txt', '1.txt', '2.txt'

最佳答案

是的,所以您确实需要添加我评论中的代码。问题是 os.listdir仅返回基本文件名,因此在调用重命名时,它希望在 Python 认为它应该位于的任何目录中找到这些文件。通过添加 os.path.join,它将构建文件的完全限定路径,因此重命名将正常工作。

在评论中,OP 表示文件被移到了一个文件夹中,这让我相信重命名需要在第二个参数上有一个完全限定的路径。此外,我们了解到不应将文件从 foo.txt 重命名为 0,而应改为 0.txt 等(保留文件扩展名)现在这段代码

import os, sys
path = input("input path: ")
dirs = os.listdir(path)
for i in range(0,len(dirs)):
# capture the fully qualified path for the original file
original_file = os.path.join(path, dirs[i])
# Build the new file name as number . file extension
# if there is no . in the file name, this code goes boom
new_file = os.path.join(path, str(i) + '.' + original_file.split('.')[-1])

print "Renaming {0} as {1}".format(original_file, new_file)
os.rename(original_file, new_file)

使用 Python 2.6.1 验证

显示命令行中的相关位。可以看到空文件 bar.txt 和 foo.txt 被重命名为 0 和 1

>>> path = input("Input path")
Input path"/Users/bfellows2/so"
>>> dirs = os.listdir(path)
>>> dirs
['bar.txt', 'foo.txt']
>>> for i in range(0,len(dirs)):
... os.rename(os.path.join(path, dirs[i]), str(i))
...
>>>
[1]+ Stopped python
Helcaraxe:so bfellows2$ ls -al
total 0
drwxr-xr-x 4 bfellows2 bfellows2 136 Sep 3 20:30 .
drwxr-xr-x 100 bfellows2 bfellows2 3400 Sep 3 20:24 ..
-rw-r--r-- 1 bfellows2 bfellows2 0 Sep 3 20:24 0
-rw-r--r-- 1 bfellows2 bfellows2 0 Sep 3 20:24 1
Helcaraxe:so bfellows2$ python -V
Python 2.6.1

关于python - 这个应该重命名文件的python代码有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7296855/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com