在Python中将所有具有不同扩展名的文件重命名为.txt

时间:2019-03-18 10:37:02

标签: python

我正在尝试根据扩展名重命名文件夹中的所有文件。我希望所有文件都为.txt格式。文件夹中的文件可以具有不同的扩展名,但是我试图将它们全部重命名为.txt

我尝试执行以下操作

allFiles = 'Path where the files are located'
for filename in glob.iglob(os.path.join(allFiles, '*.0000')):
    os.rename(filename, filename[:-5] + '.txt')

以上抛出错误:

TypeError: expected str, bytes or os.PathLike object, not list

2 个答案:

答案 0 :(得分:0)

import os


def renameFilesToTxt(input_dir):
    for path, subdirs, files in os.walk(input_dir):
        for name in files:
            filePath = os.path.join(path, name)
            target_filePath = ''.join(filePath.split('.')[:-1])+".txt"
            os.rename(filePath, target_filePath)

答案 1 :(得分:0)

我创建了一个脚本,该脚本将更改文件夹的所有文件扩展名,并且该脚本已在本地PC上进行了测试。

在您所需的文件夹中运行此脚本

import os
from pathlib import Path
items = os.listdir(".")

newlist = []
for names in items:
    if names.endswith(".0000"):
        newlist.append(names)

for i in newlist:
    print(i)
    p = Path(i)
    p.rename(p.with_suffix('.txt'))

[注意:脚本已经过测试及其工作]