【问题标题】:How to keep track of files and folders in python如何在python中跟踪文件和文件夹
【发布时间】:2021-11-03 22:28:53
【问题描述】:

我是 Python 的新手,正在研究图像分析。 在这里,我使用 python 在无头模式下运行 ilastik (https://www.ilastik.org/documentation/basics/headless.html)。 这是使用subprocess.run() 实现的。

作为其中的一部分,我需要传递各种参数,包括文件位置、关联文件的位置和任何输出文件的路径。我能够定义这些是什么,但我想知道如何保持信息链接,以便链接正确的源目录、目标目录、源文件名和相关文件名。

我想知道这里是否适合使用数据类。 这是一个简单的版本

import subprocess
import glob
from pathlib import Path
from pathlib import PurePath

ILASTIK_EXECUTABLE = (Path("E:/Program Files/ilastik-1.4.0b15/ilastik.exe"))
PROJECT_FILE = Path("D:/Burch/DNDF/RimSeg.ilp")
SOURCE_DATA = Path("D:/Burch/DNDF/")
#for item in SOURCE_DATA:
#dir = os.listdir(SOURCE_DATA)
dir = Path.iterdir(SOURCE_DATA)

source_dirs = [d for d in SOURCE_DATA.rglob("") if d.name == "processed"]
print("Source directories:", *map(str, source_dirs), sep="\n")

#Create destination directory
folder_count=0
for folder in SOURCE_DATA.rglob('**/processed/'):
    #print(folder)
    #print(folder.parent)
    out_dir=folder.parent / "probabilities"
    Path.mkdir(out_dir, parents=False, exist_ok=True)
    folder_count=folder_count+1
#for file in SOURCE_DATA.rglob('**/processed/*.tif'):
   # print(file)
#Create Outdir list
out_dirs = [d for d in SOURCE_DATA.rglob("") if d.name == "probabilities"]
print("Target directories:", *map(str, source_dirs), sep="\n") #Is there a chance that in and out get mixed up?

print (len(source_dirs))
for i in range (0, len(source_dirs)):
    if source_dirs[i].parent==out_dirs[i].parent:
        print ("dirs are matched")
print (*map(str,out_dirs), sep="\n")

def genSeg():
    common_args = [
        str(ILASTIK_EXECUTABLE),
        "--headless",
        "--readonly=1",
        "--input_axes=cyx",
        "--export_source=Simple Segmentation Stage 2",
        "--output_format=tiff",
        "--export_dtype=uint8",
        #"--export_drange=(0,255)",
        "--project="+str(PROJECT_FILE),
    ]
    source_files
    for file in source_files:
        #print (folder  / "*.tiff")
        args = [
            *common_args, #I think this concatenates the common-args list to this one. 
            "--output_filename_format="+str(file.parent.parent /  "probabilities/{nickname}_prediction.tiff"),
            #"--raw_data",
            #folder.rglob('**/processed/*.tif')
            #folder / "*.tif"
            file
        ]
        subprocess.run(map(str,args), check=True)
        print (*map(str,args), sep="\n")
        print("___________________")
        
genSeg()

我现在需要定义更多链接到源文件的文件,这些文件需要作为参数传递给subprocess.run()

关联文件的一个例子是

#define probability files
prob_file_paths=[]
for file in source_files:
    prob_file=file.name[:-4]+"_Probabilities.h5"
    #print(prob_file)
    prob_file_path=file.parent/ prob_file
    if prob_file_path.exists:
        #print (prob_file_path)
        prob_file_paths.append(prob_file_path)
    else:
        print ("file not found")
print (*map(str, prob_file_paths), sep="\n")

因此很容易创建包含信息但未链接的列表。

如何创建链接信息列表?

希望这是有道理的,

詹姆斯

【问题讨论】:

    标签: python list path python-dataclasses


    【解决方案1】:

    是的,(数据)类可能是一个解决方案。它们可以作为一般称为“记录”的东西,即将一些变量打包在一起。

    在 Python 中,数据类是一种更简单的声明常规类的方法:它会为您生成相应的__init__ 代码。

    @dataclass
    class ClassificationTask:
        source_directory_path: Path
        target_directory_path: Path
        source_filename: str
        associated_filename: str
    

    仅使用print(classification_task) 即可显示(因为数据类也自动定义了一个简洁的__str__ 方法。


    关于您的代码的一些评论(您没有要求):

    • 避免调用变量dir,因为它会影响内置函数dir(但它很少使用,因此不是真正的问题)。
    • 我不知道print(..., sep="\n"),谢谢! :)
    • args = [
          *common_args, #I think this concatenates the common-args list to this one. 
      ...
      ]
      
      它被称为 splat 运算符,它会将您的 common_args 解压缩到 args 列表中。见this answer。只是一个例子:
      >>> common_args = ["a", "b", "c"]
      >>> [common_args, "d", "e"]
      [['a', 'b', 'c'], 'd', 'e']
      >>> [*common_args, "d", "e"]
      ['a', 'b', 'c', 'd', 'e']
      
      区别在于是否使用列表本身或其值。

    【讨论】:

    • 非常感谢@Lenormju 的回答和信息丰富的附加信息。我很想知道是否有更好的方法来实现这一点。
    • @JamesBurchfield 这是一个很好的方法,如果你想要特定的东西,定义“更好”。但是对于您的问题,数据类就可以了!
    猜你喜欢
    • 2013-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-07
    • 2011-08-26
    • 2014-08-09
    • 2023-03-19
    相关资源
    最近更新 更多