我需要重命名包含许多文本文件的文件夹中的文件名。 重命名应遵循每个文件的编号顺序。 它应该像下面这样:
***given files*** ***renamed files***
abc.txt 1.txt
def.txt 2.txt
rsd.txt 3.txt
ijb.txt 4.txt
以上文件位于名为data的文件夹中
我的代码是这样的
import glob
import os
file=sorted(glob.glob("/home/prasanth/Desktop/project/prgms/dt/details/*.txt"))
fp=[]
for b in file:
fp.append(b)
i=1
for f in fp:
n=f.replace('.html','')
n=n.replace('.htm','')
m=n.replace(n,str(i)+'.txt')
i=i+1
os.rename(f,m)
我的问题是重命名后的文件正在移动到写入 python 代码的文件夹中。但是我需要将重命名的文件放在它们之前存在的同一文件夹中
请您参考如下方法:
太好了,那你尝试了什么?
作为起点,请查看 os -模块,尤其是 os.walk()和 os.rename() .
编辑:
您的文件已移动,因为您用 m=n.replace(n,str(i)+'.txt') 中的数字替换了整个路径。这会将 subfolder\textfile.txt 重命名为 1.txt,作为副作用将文件移动到当前目录。
此外,我不确定您尝试使用 htm(l)-replaces 实现什么,因为之后您用您的号码替换了所有内容。
此外,您不需要构建 txt 文件列表的副本并在之后对其进行迭代,您可以直接在原始文件列表上执行此操作。
所以这可能对你有用:
import glob
import os
filelist=sorted(glob.glob("/home/prasanth/Desktop/project/prgms/dt/details/*.txt"))
i=1
for oldname in filelist:
# ignore directories
if os.path.isfile(oldname):
# keep original path
basepath=os.path.split(oldname)[0]
newname=os.path.join(basepath, "{}.txt".format(str(i)))
i=i+1
print("Renaming {} to {}".format(oldname, newname))
os.rename(oldname, newname)
旁注:当具有新文件名的文件已经存在时,重命名将失败。您可能应该使用 try ... except 来处理它。
