我实际上是在删除或重命名包含python中问号的文件名。
是否有人会有一些指导或经验可以分享?
我的文件是这样的:
??test.txt
?test21.txt
test??1.txt
我想要的结果是:
test.txt
test21.txt
test1.txt
谢谢你的帮助。 AL
在我尝试使用以下建议的代码下方:
#!/usr/bin/python
import sys, os, glob
for iFiles in glob.glob('*.txt'):
print (iFiles)
os.rename(iFiles, iFiles.replace("?",''))
答案 0 :(得分:0)
这应该做你需要的。
import os
import sys
import argparse
parser = argparse.ArgumentParser(description='Rename files by replacing all instances of a character from filename')
parser.add_argument('--dir', help='Target DIR containing files to rename', required=True)
parser.add_argument('--value', help='Value to search for an replace', required=True)
args = vars(parser.parse_args())
def rename(target_dir, rep_value):
try:
for root, dirs, files in os.walk(target_dir):
for filename in files:
if rep_value in filename:
filename_new = str(filename).replace(rep_value, '')
os.rename(os.path.join(root, filename), os.path.join(root, filename_new))
print '{} renamed to {}'.format(filename, os.path.join(root, filename_new))
except Exception,e:
print e
target_dir = args['dir']
rep_value = args['value']
rename(target_dir, rep_value)
使用示例:
rename.py --dir /root/Python/ --value ?
<强>输出强>
?test.txt renamed to /root/Python/test.txt
?test21.txt renamed to /root/Python/test21.txt
test1?.txt renamed to /root/Python/test1.txt