【问题标题】:Moving only one file of each sub directories to new sub directories仅将每个子目录的一个文件移动到新的子目录
【发布时间】:2019-11-20 13:43:04
【问题描述】:

我对将每个子目录中的一个文件移动到其他新子目录有疑问。因此,例如,如果我有图像中显示的目录

然后,我只想选择每个子目录中的第一个文件,然后将其移动到另一个新的子目录,其名称与您从图像中看到的相同。这是我的预期结果

我已经尝试使用os.walk来选择每个子目录的第一个文件,但是我仍然不知道如何将它移动到另一个同名的子目录

path = './test/'
new_path = './x/'

n = 1
fext = ".png"

for dirpath, dirnames, filenames in os.walk(path): 
    for filename in [f for f in filenames if f.endswith(fext)][:n]:
        print(filename) #this only print the file name in each sub dir

预期结果如上图所示

【问题讨论】:

  • 结果中的新子目录在哪里?您似乎删除了第二个文件,而不是移动了第一个文件。
  • filenames[0] 是目录中的第一个文件。
  • 请参阅stackoverflow.com/questions/8858008/… 了解如何移动文件。
  • @Prune 不用shell,Python有os.rename()shutil.move()
  • 是的——好多了。我被自己的编码问题蒙蔽了双眼...... :-)

标签: python file directory path os.walk


【解决方案1】:

你快到了:)

您只需要拥有文件的完整路径:旧路径(现有文件)和新路径(您想要移动它的位置)。

正如this post 中提到的,您可以在 Python 中以不同的方式移动文件。您可以使用“os.rename”或“shutil.move”。

这是一个完整的测试代码示例:

import os, shutil

path = './test/'
new_path = './x/'

n = 1
fext = ".png"

for dirpath, dirnames, filenames in os.walk(path): 
    for filename in [f for f in filenames if f.endswith(fext)][:n]:
        print(filename) #this only print the file name in each sub dir

        filenameFull = os.path.join(dirpath, filename)
        new_filenameFull = os.path.join(new_path, filename)

        # if new directory doesn't exist - you create it recursively
        if not os.path.exists(new_path):
            os.makedirs(new_path)        

        # Use "os.rename"
        #os.rename(filenameFull, new_filenameFull)

        # or use "shutil.move"
        shutil.move(filenameFull, new_filenameFull)

【讨论】:

  • 我试过了,但它只会移动文件,而不是像上图那样创建子目录
  • 这不是问题。我已经用一个额外的块更新了我的代码。如果目录不存在,您可以创建一个目录。
猜你喜欢
  • 1970-01-01
  • 2015-09-12
  • 2016-06-09
  • 2011-07-07
  • 2023-04-07
  • 2020-05-01
  • 1970-01-01
  • 2016-04-04
  • 1970-01-01
相关资源
最近更新 更多