Python 重命名和移动文件
我已经花了相当多的时间在我下面的代码,但我就是不能让它工作,我希望有人能给我一些建议Python 重命名和移动文件,python,python-2.7,datetime,rename,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:
#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()
在每个文件夹中(例如属性
),我都有一个被取代的
文件夹。我的最终目标是重命名每个目录中的每个文件,以添加日期前缀(例如,2018010\u Property\u Export.dfb
),然后将其移动到替代的
文件夹
Property->
Property_Export.dfb
Property_Export.xls
Property_Export.shp
Supserdeded (This is a folder)
我不知道如何重命名每个文件夹中的每个文件,然后将其移动到已取代的
文件夹。目前,我想我正在尝试重命名文件路径而不是单个文件名。“U://Working\U Files”。format(x)
会导致“U://Working\U Files”
,因为字符串中没有占位符({}
)。您应该真正使用来处理路径构建。此外,您不应该将/
正斜杠加倍(您可能会将其与在Python字符串文本中需要\\
来生成单个反斜杠相混淆):
这确实是你犯的唯一逻辑错误;代码的其余部分按设计工作。也就是说,有一些事情可以改进
就我个人而言,我将把把源目录名和子目录名放在一起的工作留给函数循环。这在设置配置时为您节省了一个额外的循环
source = "U:/Working_Files"
nameList = ['Property', 'Ownership', 'Sold', 'Lease']
我不会在目录前面加~
;把它留给配置源
目录的人;它们可以显式地将~/someu目录
或~someuser/someu目录
指定为路径。函数应该使用参数,而不是全局变量。此外,在目录前面加上~
将禁止在路径的开头使用~some\u other\u account\u name
我会跳过任何不是文件的东西;不需要获取目录的修改日期,对吗
以下操作将把任何非目录名移出目录,移到名为已取代的子目录中:
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(subdir):
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)
上述措施也尽量减少工作量。只需解析一次源路径
,而不必解析子目录
中的每个名称datetime
对象支持直接格式化str.format()
格式,因此我们可以从修改后的时间戳和旧名称一步形成新文件名。os.path.abspath()
该函数不打印循环中的每个路径,而是返回已重命名文件的映射,以便调用方可以根据需要进一步处理该映射。“U://Working\U files”。format(x)
导致“U://Working\U files”
,因为字符串中没有占位符({}/code>)。您应该真正使用来处理路径构建。此外,您不应该将/
正斜杠加倍(您可能会将其与在Python字符串文本中需要\\
来生成单个反斜杠相混淆):
这确实是你犯的唯一逻辑错误;代码的其余部分按设计工作。也就是说,有一些事情可以改进
就我个人而言,我将把把源目录名和子目录名放在一起的工作留给函数循环。这在设置配置时为您节省了一个额外的循环
source = "U:/Working_Files"
nameList = ['Property', 'Ownership', 'Sold', 'Lease']
我不会在目录前面加~
;把它留给配置源
目录的人;它们可以显式地将~/someu目录
或~someuser/someu目录
指定为路径。函数应该使用参数,而不是全局变量。此外,在目录前面加上~
将禁止在路径的开头使用~some\u other\u account\u name
我会跳过任何不是文件的东西;不需要获取目录的修改日期,对吗
以下操作将把任何非目录名移出目录,移到名为已取代的子目录中:
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(subdir):
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)
上述措施也尽量减少工作量。只需解析一次源路径
,而不必解析子目录
中的每个名称datetime
对象支持直接格式化str.format()
格式,因此我们可以从修改后的时间戳和旧名称一步形成新文件名。os.path.abspath()
函数不会打印循环中的每个路径,而是返回已重命名文件的映射,以便调用者可以根据需要进一步处理该映射。查看下面的代码是否适用于您。此代码将遍历所有工作文件夹,仅查找文件,重命名这些重命名的文件并将其移动到被取代的文件夹中
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}'))
看看下面的代码是否适合您。此代码将遍历所有工作文件夹,仅查找文件,重命名这些重命名的文件并将其移动到被取代的文件夹中
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}'))
你的问题有点让人困惑,因为“重命名”一个文件和“移动”一个文件之间没有区别。@larsks:我不认为这有那么让人困惑。重命名父路径与重命名文件名本身通常被视为两个独立的操作。我同意。你的问题有点让人困惑,因为“重命名”文件和“移动”文件之间没有区别。@larsks:我不认为这有那么让人困惑。重命名父路径与重命名文件名本身通常被视为两个独立的操作。我同意。这将/Property\u Export.dfb
移动到/supersed/2018010\u Property\u Export.dfb\u Export.dfb
,并忽略修改的日期。并且os.rename()
足以移动文件,为什么还要使用shutil.move()
shutil.move
对于移动文件层次结构很有用,不是吗