Change the file extension for files in a folder?
我想更改特定文件夹中文件的扩展名。我在论坛上读到这个话题。使用does-ideas,我已经编写了以下代码,我希望它可以工作,但它不能。如果有人指导我找出错误,我将不胜感激。
1 2 3 4 5 6 7 8 9 10 | import os,sys folder = 'E:/.../1936342-G/test' for filename in os.listdir(folder): infilename = os.path.join(folder,filename) if not os.path.isfile(infilename): continue oldbase = os.path.splitext(filename) infile= open(infilename, 'r') newname = infilename.replace('.grf', '.las') output = os.rename(infilename, newname) outfile = open(output,'w') |
源文件上的
1 2 3 4 5 6 7 8 | import os,sys folder = 'E:/.../1936342-G/test' for filename in os.listdir(folder): infilename = os.path.join(folder,filename) if not os.path.isfile(infilename): continue oldbase = os.path.splitext(filename) newname = infilename.replace('.grf', '.las') output = os.rename(infilename, newname) |
我只是简单地去掉了两个
您不需要打开文件来重命名它们,
1 2 3 4 | import glob, os for filename in glob.iglob(os.path.join(folder, '*.grf')): os.rename(filename, filename[:-4] + '.las') |
类似这样的操作会将执行目录中以.txt结尾的所有文件重命名为.text。
1 2 3 4 5 6 | import os, sys for filename in os.listdir(os.path.dirname(os.path.abspath(__file__))): base_file, ext = os.path.splitext(filename) if ext ==".txt": os.rename(filename, base_file +".text") |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | #!/usr/bin/env python ''' Batch renames file's extension in a given directory ''' import os import sys from os.path import join from os.path import splitext def main(): try: work_dir, old_ext, new_ext = sys.argv[1:] except ValueError: sys.exit("Usage: {} directory old-ext new-ext".format(__file__)) for filename in os.listdir(work_dir): if old_ext == splitext(filename)[1]: newfile = filename.replace(old_ext, new_ext) os.rename(join(work_dir, filename), join(work_dir, newfile)) if __name__ == '__main__': main() |