重命名和移动文件

时间:2018-01-10 14:34:57

标签: python python-2.7 datetime rename

我花了很多时间在我的代码上,但我无法让它工作,我希望有人可以给我一些建议。

#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文件夹。

Property->
    Property_Export.dfb
    Property_Export.xls
    Property_Export.shp
    Supserdeded (This is a folder)

我不确定如何重命名每个文件夹中的每个文件,然后将其移至superseded文件夹。目前我认为我正在尝试重命名文件路径而不是单个文件名。

2 个答案:

答案 0 :(得分:2)

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

import os.path

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

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

就个人而言,我将把源目录名和子目录名一起放到函数循环中。只需设置配置即可为您节省额外的循环。

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

我不会在目录前添加~;把它留给任何配置source目录的人;他们可以明确指定~/some_directory~someuser/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()也会清除//双斜杠等错误,使其更加健壮。

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

答案 1 :(得分:-1)

查看以下代码是否适合您。此代码将遍历所有工作文件夹,仅查找文件,重命名并将这些重命名的文件移动到已取代的文件夹

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}'))