【问题标题】:Copying files with a specific name to another folder将具有特定名称的文件复制到另一个文件夹
【发布时间】:2021-05-20 15:04:10
【问题描述】:

我有 1500 个 txt 文件的文件夹和 20000 个 jpg 文件的文件夹。 1500 个 jpg 文件与 txt 文件命名相同。我需要将这些名称类似于 txt 文件的 jpg 文件移动到另一个文件夹。 简单来说,我有 txt 文件从 1(1) 到 5(500),我只需要从 jpg 文件从 0(1) 的文件夹中移动名称从 1(1) 到 5(500) 的文件至 9(500)。 我尝试通过shutil用Python编写程序,但我不明白如何输入所有1500 valuse,因此只有这些文件被移动。 请告诉我该怎么做?提前致谢! 我找到了所有txt文件的名称,并试图从另一个文件夹中复制具有相同名称的图片。 图片上的示例: 我有这个名字 我只需要复制这些图像,因为它们的名称与 txt 的名称相同:

import os
import glob
import shutil


source_txt = 'C:\obj\TXT'
dir = 'C:\obj\Fixed_cars'
vendors =['C:\obj\car']

files_txt = [os.path.splitext(filename)[0] for filename in os.listdir(source_txt)]

for file in vendors:
     for f in (glob.glob(file)):
         if files_txt in f: # if apple in name, move to new apple dir
             shutil.move(f, dir)

【问题讨论】:

  • 请向我们展示您已经编写的内容,并进一步说明该代码的哪些部分没有按照您的意愿执行。另外,请给我们一些应该/不应该匹配/复制的文件名示例。

标签: python copy shutil


【解决方案1】:

好吧,使用this answer on looping through files of a folder 您可以循环浏览文件夹中的文件。

import os

directory = ('your_path_in_string')
txt_files = []
for filename in os.listdir(directory):
    if filename.endswith(".txt"): 
         txt_files.append(filename.rstrip('.txt'))
for filename in os.listdir(directory):
    if (filename.endswith(".jpg") and (filename.rstrip('.jpg') in txt_files)): 
         os.rename(f"path/to/current/{filename}", f"path/to/new/destination/for/{filename}")

for the the moving file part you can read this answer

【讨论】:

  • 感谢您的解决方案,这对我有用!
猜你喜欢
  • 1970-01-01
  • 2022-10-05
  • 2016-06-06
  • 1970-01-01
  • 2021-12-10
  • 1970-01-01
  • 1970-01-01
  • 2017-04-16
  • 2017-03-01
相关资源
最近更新 更多