我已经花了相当长的时间在我的下面的代码,但我不能让它工作,我希望有人能给我一些建议。在
#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
文件夹中。在
我不知道如何重命名每个文件夹中的每个文件,然后将其移动到superseded
文件夹。目前,我想我是在尝试重命名文件路径,而不是单个文件名。在
看看下面的代码是否适合您。此代码将遍历所有工作文件夹,只查找文件,重命名并将重命名的文件移动到被取代的文件夹中
"U://Working_Files".format(x)
导致"U://Working_Files"
,因为字符串中没有占位符({}
)。您应该使用^{/
正斜杠加倍(您可能会将这与在Python字符串文本中生成单个反斜杠所需的\\
混淆):这实际上是您所犯的唯一逻辑错误;其余代码确实按设计工作。也就是说,有一些事情可以改进。在
就个人而言,我将把源目录名和子目录名放在一起的工作留给函数循环。这为您在设置配置时节省了一个额外的循环。在
^{pr2}$我不会在目录前面加上}作为路径。函数应该接受参数,而不是使用全局变量。此外,在目录前面加上
~
;把这个留给配置source
目录的人;他们可以显式地指定~/some_directory
或{~
将不允许在这样一个路径的开头使用~some_other_account_name
。在我早就跳过那些不是文件的内容;不需要获取目录的修改日期,对吗?在
以下操作将把任何非目录名移出目录,放入名为
superseded
的子目录中:上述措施也尽量减少工作量。您只需要解析
source
路径一次,而不是针对subdirs
中的每个名称。datetime
对象直接支持str.format()
格式,因此我们可以从修改后的时间戳和旧名称一步形成新的文件名。os.path.abspath()
还清除了//
双斜杠之类的错误,使其更加健壮。在该函数不打印循环中的每个路径,而是返回已重命名文件的映射,因此调用者可以根据需要进一步处理该映射。在
相关问题 更多 >
编程相关推荐