Python 删除文件夹中所有文件中的所有编号
我正在尝试创建一个python脚本,它将进入一个特定的文件夹,并从文件名中删除所有数字 这是密码Python 删除文件夹中所有文件中的所有编号,python,python-2.7,Python,Python 2.7,我正在尝试创建一个python脚本,它将进入一个特定的文件夹,并从文件名中删除所有数字 这是密码 def rename_file(): print"List of Files:" print(os.getcwd()) os.chdir("/home/n3m0/Desktop/Pictures") for fn in os.listdir(os.getcwd()): print("file w/ numbers -" +fn) print("File w/o numbers
def rename_file():
print"List of Files:"
print(os.getcwd())
os.chdir("/home/n3m0/Desktop/Pictures")
for fn in os.listdir(os.getcwd()):
print("file w/ numbers -" +fn)
print("File w/o numbers - "+fn.translate(None, "0123456789"))
os.rename(fn, fn.translate(None, "0123456789"))
os.chdir("/home/n3m0/Desktop/Pictures")
rename_files()
我要做的是删除所有的数字,这样我就可以读取文件名
例如,我想要:
B45608aco4897n Pan44ca68ke90s1.jpg
意思是说培根煎饼.jpg
当我运行脚本时,它会更改终端中的所有名称,但当我转到文件夹时,只有一个文件名已更改,我必须多次运行脚本。我使用的是python 2.7。我不是100%了解这一点,因为我现在正在使用手机,但请尝试以下方法:
from string import digits
def rename_files():
os.chdir("/whatever/directory/you/want/here")
for fn in os.listdir(os.getcwd()):
os.rename(fn, fn.translate(None, digits))
rename_files()
你的缩进有点乱,这是造成问题的部分原因。您也不一定需要更改工作目录-我们只需跟踪正在查看的文件夹,然后使用
os.path.join
重新构建文件路径,如下所示:
import os
from string import digits
def renamefiles(folder_path):
for input_file in os.listdir(folder_path):
print 'Original file name: {}'.format(input_file)
if any(str(x) in input_file for x in digits):
new_name = input_file.translate(None, digits)
print 'Renaming: {} to {}'.format(input_file, new_name)
os.rename(os.path.join(folder_path, input_file), os.path.join(folder_path, new_name))
rename_files('/home/n3m0/Desktop/Pictures')
这就产生了一种可以重复使用的方法——我们循环遍历文件夹中的所有项目,边打印原始名称。然后我们检查文件名中是否有数字,如果有,我们将重命名文件
但是,请注意,这种方法并不特别安全-如果文件名完全由数字和扩展名组成怎么办?如果有两个文件的名称与数字不同(例如asongtoruin0.jpg
和asongtoruin1.jpg
),该怎么办?此方法将只保留找到的最后一个文件,覆盖第一个文件。查看os
中可用的函数,尝试解决此问题,尤其是os.path.isfile
编辑:有一些空闲时间,这里有一个小补丁来捕获重命名为现有文件名时出现的错误:
def renamefiles(folder_path):
for input_file in os.listdir(folder_path):
print 'Original file name: {}'.format(input_file)
if any(str(x) in input_file for x in digits):
new_name = input_file.translate(None, digits)
# if removing numbers conflicts with an existing file, try adding a number to the end of the file name.
i = 1
while os.path.isfile(os.path.join(folder_path, new_name)):
split = os.path.splitext(new_name)
new_name = '{0} ({1}){2}'.format(split[0], i, split[1])
print 'Renaming: {} to {}'.format(input_file, new_name)
os.rename(os.path.join(folder_path, input_file), os.path.join(folder_path, new_name))
rename_files('/home/n3m0/Desktop/Pictures')
在这里以正确的格式发布您的代码,而不是在图片中。当您使用图像时,请将其内联(单击图像按钮,而不是链接按钮)很抱歉,我很新这里的“删除数字”是指“删除数字字符(0-9)”,对吗?您对
os.rename
的调用不在for
循环的范围内-因此只有for
循环找到的最后一个文件被重命名。这也起作用了,但是我的os.rename()函数不在for循环的范围内