重命名和移动文件

2024-09-29 23:28:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经花了相当长的时间在我的下面的代码,但我不能让它工作,我希望有人能给我一些建议。在

#Example Code
import os, datetime
source = "U://Working_Files"
nameList=["U://Working_Files".format(x) for x in ['Property','Ownership','Sold','Lease']]
def Rename_and_move_files():
    for name in nameList:
        path=os.path.expanduser(os.path.join("~",name))
        dirList=os.listdir(path)
        for filename in dirList:
            filePath=os.path.join(path,filename)
            modified_time=os.path.getmtime(name)
            modified_date=datetime.date.fromtimestamp(modified_time)
            correct_format=modified_date.strftime('%Y%m%d')
            if os.path.isfile(filePath):
                new_name = correct_format + '_' + filename
                destPath=os.path.join(path, "superseded", new_name)
                print destPath
                os.rename(filePath, new_name)



Rename_and_move_files()

在每个文件夹中(例如,Property)我有一个superseded文件夹。我的最终目标是重命名每个目录中的每个文件以添加日期前缀(例如2018010_Property_Export.dfb),然后将其移动到superseded文件夹中。在

^{pr2}$

我不知道如何重命名每个文件夹中的每个文件,然后将其移动到superseded文件夹。目前,我想我是在尝试重命名文件路径,而不是单个文件名。在


Tags: pathnamein文件夹formatnewfordate
2条回答

看看下面的代码是否适合您。此代码将遍历所有工作文件夹,只查找文件,重命名并将重命名的文件移动到被取代的文件夹中

import os
import shutil

working_folders = [f'C:\working_folders\{x}' for x in ['Property','Ownership','Sold','Lease']]

for wf in working_folders:
    for f in os.listdir(wf):
        if os.path.isfile(os.path.join(wf, f)):
            os.rename(os.path.join(wf, f), os.path.join(wf, f'2018010_Property_Export.dfb_{f}'))
            shutil.move(os.path.join(wf, f'2018010_Property_Export.dfb_{f}'), os.path.join(wf, 'superseded', f'2018010_Property_Export.dfb_{f}'))

"U://Working_Files".format(x)导致"U://Working_Files",因为字符串中没有占位符({})。您应该使用^{}来处理路径构建。另外,您不应该将/正斜杠加倍(您可能会将这与在Python字符串文本中生成单个反斜杠所需的\\混淆):

import os.path

source = "U:/Working_Files"
nameList = [os.path.join(source, name) for name in ['Property', 'Ownership', 'Sold', 'Lease']]

这实际上是您所犯的唯一逻辑错误;其余代码确实按设计工作。也就是说,有一些事情可以改进。在

就个人而言,我将把源目录名和子目录名放在一起的工作留给函数循环。这为您在设置配置时节省了一个额外的循环。在

^{pr2}$

我不会在目录前面加上~;把这个留给配置source目录的人;他们可以显式地指定~/some_directory或{}作为路径。函数应该接受参数,而不是使用全局变量。此外,在目录前面加上~将不允许在这样一个路径的开头使用~some_other_account_name。在

我早就跳过那些不是文件的内容;不需要获取目录的修改日期,对吗?在

以下操作将把任何非目录名移出目录,放入名为superseded的子目录中:

import os
import os.path
import datetime

def rename_and_move_files(source, subdirs, destination_subdir):
    """Archive files from all subdirs of source to destination_subdir

    subdirs is taken as a list of directory names in the source path, and
    destination_subdir is the name of a directory one level deeper. All files
    in the subdirectories are moved to the destination_subdir nested directory,
    renamed with their last modification date as a YYYYMMDD_ prefix.

    For example, rename_and_move_files('C:\', ['foo', 'bar'], 'backup') moves
    all files in the C:\foo to C:\foo\backup, and all files in C:\bar to 
    C:\bar\backup, with each file prefixed with the last modification date.
    A file named spam_ham.ext, last modified on 2018-01-10 is moved to
    backup\20180110_spam_ham.ext.

    source is made absolute, with ~ expansion applied.

    Returns a dictionary mapping old filenames to their new locations, using
    absolute paths.

    """
    # support relative paths and paths starting with ~
    source = os.path.abspath(os.path.expanduser(source))

    renamed = {}

    for name in subdirs:
        subdir = os.path.join(source, name)
        destination_dir = os.path.join(subdir, destination_subdir)
        for filename in os.listdir(destination_dir):
            path = os.path.join(subdir, filename)

            if not os.path.isfile(path):
                # not a file, skip to the next iteration
                continue

            modified_timestamp = os.path.getmtime(path)
            modified_date = datetime.date.fromtimestamp(modified_timestamp)
            new_name = '{:%Y%m%d}_{}'.format(modified_date, filename)
            destination = os.path.join(destination_dir, new_name)
            os.rename(path, destination)
            renamed[path] = destination

    return renamed

source = "U:/Working_Files"
name_list = ['Property', 'Ownership', 'Sold', 'Lease']

renamed = rename_and_move_files(source, name_list, 'superseded')
for old, new in sorted(renamed.items()):
    print '{} -> {}'.format(old, new)

上述措施也尽量减少工作量。您只需要解析source路径一次,而不是针对subdirs中的每个名称。datetime对象直接支持str.format()格式,因此我们可以从修改后的时间戳和旧名称一步形成新的文件名。os.path.abspath()还清除了//双斜杠之类的错误,使其更加健壮。在

该函数不打印循环中的每个路径,而是返回已重命名文件的映射,因此调用者可以根据需要进一步处理该映射。在

相关问题 更多 >

    热门问题