0

我想将扩展名为“.test.txt”的文件更改为“.txt”。如下我的代码,它不能工作,因为'if'的地方发生了无效的语法。你能弄清楚吗?太感谢了。

import sys
import os

path = "Dir"
for(dirpath,dirnames,files)in os.walk(path):
   for filename in files:
           filepath = os.path.join(dirpath,filename)
    if '.test.txt' in filename:
           newfilename = filename.replace('.test.txt','.txt')
           os.rename(filename,newfilename)
4

1 回答 1

1

这应该工作......

import sys
import os

path = r"Dir"
for dirpath,dirnames,files in os.walk(path):
    for filename in files:
        filepath = os.path.join(dirpath,filename)
        if '.test.txt' in filename:
            newfilename = filename.replace('.test.txt','.txt')
            newfilepath = os.path.join(dirpath, newfilename)
            os.rename(filepath, newfilepath)

您没有定义新的文件路径,在重命名操作中您必须提供完整的文件路径,os.rename(src_path, dest_path)

于 2013-06-05T16:27:06.937 回答