Python 使用子字符串重命名文件名最佳实践
Python Rename Filename With Substring Best Practices
简化了,我有一个数据文件:
P.A2057.ACO.QASSGN.D150218.T1200333.xls
我成功地将其复制到目录 "MSSP_DATA_ARCHIVE" 以在此处获取文档:
dest_dir = "C:/Users/Office/Desktop/TEST/MSSP_DATA_ARCHIVE/"
for file in glob.glob(r'C:/Users/Office/Desktop/TEST/LOAD/*.xls'):
print file
shutil.copy(file, dest_dir)
我想将 "LOAD" 中的原始版本重命名为:
QASSGN.xls
我不会知道每月文件的确切名称(似乎至少是部分随机生成的某些元素)。
我希望对当前文件名进行子字符串化以提取上面所需的名称。
这是我开始的:
for file in glob.glob(r'C:/Users/Office/Desktop/TEST/LOAD/*.xls'):
parts = file.split('.')
parts = ['C:/Users/Office/Desktop/TEST/LOAD\P',
'A2057', 'ACO', 'QASSGN', 'D150218', 'T1200333','xls']
我知道必须有更好的方法来处理 os.path.splitext 和 os.rename 以避免陷入 "magic numbers" 麻烦。不是很蟒蛇。
任何指点将不胜感激!
这是假设您的输入始终是您想要的名称作为文件名中的第 4 部分。只有一件事是一个神奇的数字,因为我不知道你希望你的数据被命名的另一种方式。
# the path of your files
path = 'C:\Users\Office\Desktop\TEST\LOAD'
# the place you want to output your files
# set to input because i have no idea where you want them
dest_path = path
# the type of files you want to rename
ext = r'xls'
# file will contain the path of the file
for file in glob.glob('{path}\*.{ext}'.format(path=path, ext=ext)):
# the filename we are going to change (dont want the path at all)
name = file.split('\')[-1]
# the new name of the file
new_file = '{path}\{name}.{ext}'.format(
path=dest_path,
name=name.split('.')[3],
ext=ext
)
os.rename(file, new_file)
简化了,我有一个数据文件:
P.A2057.ACO.QASSGN.D150218.T1200333.xls
我成功地将其复制到目录 "MSSP_DATA_ARCHIVE" 以在此处获取文档:
dest_dir = "C:/Users/Office/Desktop/TEST/MSSP_DATA_ARCHIVE/"
for file in glob.glob(r'C:/Users/Office/Desktop/TEST/LOAD/*.xls'):
print file
shutil.copy(file, dest_dir)
我想将 "LOAD" 中的原始版本重命名为:
QASSGN.xls
我不会知道每月文件的确切名称(似乎至少是部分随机生成的某些元素)。
我希望对当前文件名进行子字符串化以提取上面所需的名称。
这是我开始的:
for file in glob.glob(r'C:/Users/Office/Desktop/TEST/LOAD/*.xls'):
parts = file.split('.')
parts = ['C:/Users/Office/Desktop/TEST/LOAD\P',
'A2057', 'ACO', 'QASSGN', 'D150218', 'T1200333','xls']
我知道必须有更好的方法来处理 os.path.splitext 和 os.rename 以避免陷入 "magic numbers" 麻烦。不是很蟒蛇。
任何指点将不胜感激!
这是假设您的输入始终是您想要的名称作为文件名中的第 4 部分。只有一件事是一个神奇的数字,因为我不知道你希望你的数据被命名的另一种方式。
# the path of your files
path = 'C:\Users\Office\Desktop\TEST\LOAD'
# the place you want to output your files
# set to input because i have no idea where you want them
dest_path = path
# the type of files you want to rename
ext = r'xls'
# file will contain the path of the file
for file in glob.glob('{path}\*.{ext}'.format(path=path, ext=ext)):
# the filename we are going to change (dont want the path at all)
name = file.split('\')[-1]
# the new name of the file
new_file = '{path}\{name}.{ext}'.format(
path=dest_path,
name=name.split('.')[3],
ext=ext
)
os.rename(file, new_file)