扫描目录并传输文件

时间:2017-05-15 07:27:47

标签: python

我认为这很简单但我的脚本不起作用。我认为如果我告诉你我想要的东西会更容易:我想要一个脚本(在python中)这样做:

我有一个目录,如:

boite_noire/
....helloworld/
....test1.txt/
....test2.txt/

在运行脚本之后,我想要像:

boite_noire/
helloworld/
....test1/
........test1_date.txt
....test2/
........test2_date.txt

如果我添加其他test1.txt,如:

boite_noire/
helloworld/
....test1/
........test1_date.txt
....test2/
........test2_date.txt
....test1.txt

下次我运行脚本时:

boite_noire/
helloworld/
....test1/
........test1_date.txt
........test1_date.txt
....test2/
........test2_date.txt

我写了这个剧本:

script

os.walk读取目录中的文件,然后创建一个名为该文件的目录,我不想要:(

有人能帮助我吗?

1 个答案:

答案 0 :(得分:0)

您可以遍历每个文件并将其移动到正确的目录中。这将适用于Linux系统(不确定Windows - 可能更好地使用 shutil.move 命令)。

import os
import time

d = 'www/boite_noire'

date = time.strftime('%Y_%m_%d_%H_%M_%S')
filesAll = os.listdir(d)
filesValid= [i for i in filesAll if i[-4:]=='.txt']

for f in filesValid:

    newName = f[:-4]+'_'+date+'.txt'
    try:
        os.mkdir('{0}/{1}'.format(d, f[:-4]))
    except:
        print 'Directory {0}/{1} already exists'.format(d, f[:-4])
    os.system('mv {0}/{1} {0}/{2}/{3}'.format(d, f, f[:-4], newName))

这就是代码正在做的事情:

  • 查找指定目录中的所有文件
  • 检查扩展程序是 .txt
  • 对于每个有效文件:
    • 通过附加日期/时间
    • 创建新名称
    • 创建目录(如果存在)
    • 将文件移动到目录中(在移动时更改名称)
相关问题