【问题标题】:Select specific files with their name in folders then manipulate them (Python)在文件夹中选择具有其名称的特定文件,然后对其进行操作(Python)
【发布时间】:2022-04-13 01:00:33
【问题描述】:

我正在尝试编写一个脚本来从几个文件夹中的名称中选择特定文件,然后将这些文件复制到一个新文件夹中。

更准确地说,我有一个包含 29 个文件夹的目录,每个文件夹中有数百个 '*.fits' 文件。

我想在这些 fit 文件中选择 .fits 之前最后 3 位数字中没有数字“4”或“8”的文件

例如:“ngc6397id016000520jd2456870p5705f002.fits”在扩展名 .fits 前的最后三位数字为“002”

我有点迷路了,因为我对此很陌生,有人可以帮忙吗?

谢谢!

【问题讨论】:

  • 欢迎来到 StackOverflow!请编辑您的问题,以在您的解决方案尝试中包含您迄今为止编写的代码。这将使您的问题更有可能得到回答。

标签: python-3.x


【解决方案1】:
import os
import shutil

data_path = ".<your directory with 29 folders>"
data_dir = os.listdir(data_path)
# for each folder in the directory
for fits_dir in data_dir:
    fits_path = data_path + "/" + log_dir + "/"
    # for each .fits file in the folder
    for file in os.listdir(fits_path):
        # if neither 4 or 8 are in the last 3 digits before the dot 
        if '4' not in file.split(".")[0][-3:] and '8' not in file.split(".")[0][-3:]:
             shutil.copy(fits_path + "/" + file, destination)

【讨论】:

  • 非常感谢,我只需要添加一行就可以了!效果很好!
【解决方案2】:

SO 用于代码帮助,但是,这应该可以帮助您入门。

下面的代码将通过遍历所有子目录和包含的文件打印出所需的文件。您必须对此代码进行改进才能使其可靠;但是,例如错误和大小写检查,它将有助于您继续前进。

import os

TARGET_DIR = r"C:\yourDir"
IGNORE_NUM = ['4', '8']

for path, dirs, files in os.walk(TARGET_DIR):
    for index, file in enumerate(files):
        fileSplit = os.path.splitext(file)
        if(fileSplit[1] != ".fits"):
            continue
        lastThree = fileSplit[0][-3:]
        if(set(IGNORE_NUM).intersection(set(lastThree))):
            continue
        print(f"[{index}] {file}")

从此,使用shutil 库将文件复制到您想要的目录是很简单的。

shutil.copyfile(src, dst)

结合所有这些,你就有了你的脚本。

【讨论】:

  • 我试过你的代码,虽然我用的不是这个,但它对我有帮助,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多