Python 更改文件夹中文件的文件扩展名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16736080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change the file extension for files in a folder?
提问by user2355306
I would like to change the extension of the files in specific folder. i read about this topic in the forum. using does ideas, I have written following code and I expect that it would work but it does not. I would be thankful for any guidance to find my mistake.
我想更改特定文件夹中文件的扩展名。我在论坛上读到了这个话题。使用确实的想法,我编写了以下代码,我希望它会起作用,但不会。我将感谢任何指导以找出我的错误。
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')
采纳答案by chenaren
The openon the source file is unnecessary, since os.renameonly needs the source and destination paths to get the job done. Moreover, os.renamealways returns None, so it doesn't make sense to call openon its return value.
在open对源文件是不必要的,因为os.rename只需要在源和目标路径来完成这项工作。此外,os.rename总是返回None,所以调用open它的返回值是没有意义的。
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)
I simply removed the two open. Check if this works for you.
我只是删除了两个open. 检查这是否适合您。
回答by kelsmj
Something like this will rename all files in the executing directory that end in .txt to .text
这样的事情会将执行目录中以 .txt 结尾的所有文件重命名为 .text
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")
回答by elyase
回答by Ricky Wilson
#!/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()
回答by Jagdish
import os
导入操作系统
dir =("C:\Users\jmathpal\Desktop\Jupyter\Arista")
for i in os.listdir(dir):
files = os.path.join(dir,i)
split= os.path.splitext(files)
if split[1]=='.txt':
os.rename(files,split[0]+'.csv')

