我正在学习如何在Python 2.7.13上编码,我很喜欢它!但是,我被困住了,想寻求你的帮助。
我正在关注此视频:https://www.youtube.com/watch?v=TMw5EzdIucE
任务是重命名文件夹中的文件,以便每个文件标题中都没有数字。
这是我的代码不起作用:
import os
# step 1) find files in folder
for file in os.listdir("/Users/applereciate/Downloads/prank"):
filelist = print(file)
os.chdir("/Users/applereciate/Downloads/prank")
# step 2) for each file, rename filename
os.rename(filelist, filelist.translate(None, "0123456789"))
这是教师的代码,对我来说也不起作用:
import os
def rename_files():
#question 1: is it really necessary to define a function to solve this problem?
# step 1) find files in folder
file_list = os.listdir("/Users/applereciate/Downloads/prank"):
saved_path = os.getcwd()
print("current working directory is "+saved_path)
os.chdir("/Users/applereciate/Downloads/prank")
# step 2) for each file, rename filename
for file_name in file_list:
#question 2: does this line make filename a file in filelist? so that it assumes that all files in filelist are now under the variable "filename"?
os.rename(file_name, file_name.translate(None, "0123456789"))
os.chdir(saved_path)
renamefiles()
#question 3: what's the purpose of this line above?
我很想知道为什么我的代码不起作用,所以请随时给我你诚实的想法。
答案 0 :(得分:0)
文件名在file
,因此请使用它:
os.rename(file, file.translate(None, "0123456789"))
但如果你真的想出去做导师,请完全跳过chdir并考虑边缘条件。
import os
import re
basedir = "/Users/applereciate/Downloads/prank"
# does this directory exist?
if os.path.isdir(basedir):
for fn in os.listdir(basedir):
# Note: There are several ways to remove digits:
# python 2.x
# newfn = fn.translate(None, "0123456789")
# python 3.x (but make trans outside the loop...)
# trans = {ord(c):None for c in '0123456789'}
# newfn = fn.translate(trans)
# something that works in 2 and 3
newfn = re.sub(r'\d+', '', fn)
# don't bother with a rename if there wasnt a translation
if newfn != fn:
# don't chdir, just set your paths up right
absfrom = os.path.join(basedir, fn)
absto = os.path.join(basedir, newfn)
# ignore subdirectories
if os.isfile(absfrom):
# see if we are overwriting anything
if os.path.exists(absto):
print('ERROR: Name collision', absto)
else:
os.rename(absfrom, absto)