Python 2.7 Python使用子字符串重命名文件名最佳实践

Python 2.7 Python使用子字符串重命名文件名最佳实践,python-2.7,etl,Python 2.7,Etl,简而言之,我有一个数据文件: 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 shu

简而言之,我有一个数据文件:

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)
我想将仍处于“加载”状态的原始版本重命名为:

我不知道每月文件的确切名称(对于某些元素,似乎至少部分是随机生成的)

我希望用当前文件名的子字符串来提取上面所需的名称

以下是我的开始:

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.splitextos.rename可以避免陷入“神奇数字”的麻烦。不是很像蟒蛇


任何指点都将不胜感激

这是假设您的输入始终作为您所需的名称作为文件名的第四部分。唯一的一件事是一个神奇的数字,因为我不知道你希望你的数据被命名的另一种方式

# 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)

我想你有太多与这里无关的细节,但我知道的不足以编辑这篇文章。您的问题似乎归结为将具有特定名称格式的文件重命名为不同的名称格式。这是正确的吗?只是提供上下文。我会把它砍下来一点。的确,您是对的。如果它始终是您想要使用的第四个组件,那么您可能会感兴趣的是类似于
newname='...join([file.split('.')[3],'xls'])
的内容,再加上带有适当参数的后续
os.rename(…)
(或来自
shutil
的相关调用,因为您已经在使用它)…您试图将文件重命名为什么?最好有两个左右的预期输入(尽可能不同)和输出示例like@twalberg这无疑为我指明了正确的方向,让我在glob.glob中找到文件(r'C:/Users/Office/Desktop/TEST/LOAD/*.xls'):新的_名称='.'。.连接([file.split('..)[3],'xls'])操作系统.重命名('C:/Users/Office/Desktop/TEST/LOAD/*.xls',新的_名称)但问题是os.rename需要确切的名称/路径,因为原始文件名中有随机数,所以我尽量避免使用该名称/路径。这对我来说非常有用。我只想将其保存在当前文件夹中,因此它可以完美地工作。不必担心奇异的幻数。我只是在寻找最佳做法建议。这对于我的大量用例,我将是一个干净的方法。对于最初的细节过载,我深表歉意。
# 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)