【问题标题】:Script to rename and copy files to a new directory.用于重命名文件并将其复制到新目录的脚本。
【发布时间】:2012-03-22 09:28:53
【问题描述】:

您好,我最近制作了这个脚本来重命名我扫描的带有前缀和日期的文件。它工作得很好,但是如果它可以在当前目录中创建一个与第一个文件同名的目录,然后将所有扫描的文件移动到那里,那就太好了。例如。第一个文件重命名为“Scanned As At 22-03-2012 0”,然后一个名为“Scanned As At 22-03-2012 0”的目录(路径为 M:\Claire\Scanned As At 22-03-2012 0)制作并且该文件被放置在那里。

我很难找出最好的方法来做到这一点。提前致谢!

import os
import datetime
#target = input( 'Enter full directory path: ')
#prefix = input( 'Enter prefix: ')
target = 'M://Claire//'
prefix = 'Scanned As At '
os.chdir(target)
allfiles = os.listdir(target)
count = 0
for filename in allfiles:
    t = os.path.getmtime(filename)
    v = datetime.datetime.fromtimestamp(t)
    x = v.strftime( ' %d-%m-%Y')
    os.rename(filename, prefix + x + " "+str(count) +".pdf")
    count +=1

【问题讨论】:

  • 问题在哪里?似乎您知道该怎么做,并且已经完成了大部分工作。
  • 对不起,我可能应该更清楚。我很难弄清楚如何以与文件相同的名称格式重命名文件夹并实际制作文件夹。

标签: python-3.x python


【解决方案1】:

不太清楚您的要求。如果不重命名文件,只把它放在目录下,那么你可以使用下面的代码(只有你的例子的for循环):

for filename in allfiles:
    if not os.isfile(filename): continue
    t = os.path.getmtime(filename)
    v = datetime.datetime.fromtimestamp(t)
    x = v.strftime( ' %d-%m-%Y')
    dirname = prefix + x + " " + str(count)
    target = os.path.join(dirname, filename)
    os.renames(filename, target)
    count +=1

您可以查看help(os.renames)

【讨论】:

    猜你喜欢
    • 2012-02-26
    • 2013-08-25
    • 2015-04-08
    • 2011-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-18
    • 1970-01-01
    相关资源
    最近更新 更多