在Python中读取txt文件并按名称执行操作

2024-09-25 00:29:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类似于txt的txt文件,但是有更多的行。你知道吗

我想要一个主文件夹的目录,其中包含子文件夹,每个子文件夹包含ASTIK.shpASTIK子文件夹中,然后是EAS.shp,在EAS子文件夹中,然后是ASTOM.shp,等等

INT表示与此代码执行交集,在这种情况下,应该涉及ASTIKEAS形状文件。你知道吗

例如,行:

INT_ASTIK_EAS  

暗示:

import geopandas
inte_s=gpd.overlay(ASTIK,EAS,how='intersection')

然后转到另一行并“理解”该行的含义,并在两个命名的shapefile之间执行擦除(差异)。你知道吗

如果文件名前面有ER,例如:

ER_ASTOM_ASTIK

它应该执行:

 er=gpd.overlay(ASTOM,ASTIK,how='difference')

然后找到确切的文件并执行它。我该怎么做而不需要做很多条件和一行一行的:比如

directory=input('Insert dir of the main folder')
txtfile=open(input()) #insert directory of txt
x = txtfile.readlines()
txtfile.close()

这将在用户提供的路径中查找通常包含SHP的目录:

import os
import fiona
rootdir = r'C:\Users\user\Desktop\a' # path to your root directory you walk
sfiles = [] # a list with all the .shp files
for entry in os.listdir(rootdir):
    dirpath = os.path.join(rootdir, entry)
    if os.path.isdir(dirpath): 
        for file in os.listdir(dirpath): # Get all files in the subdirectories
            if file.endswith('.shp'): # If it's an .shp.
                filepath = os.path.join(dirpath, file)
                sfiles.append(fiona.open(filepath))

然后不知怎么的 将txt中的单词与所述文件的相应计算(交集或差分)相连接。你知道吗

从这样的代码:(我知道错误,但只是给一个想法)

    If 'INT' in firstline of txt in directory and ASTOM and EAS:
        perform intersection between those.

我不认为唯一的办法是制造恐惧的if条件,可能永远不会有效。你知道吗

我该怎么做呢?你知道吗

txt中提到的文件很有可能是失踪了。我的不提不好它。它需要异常和声明此特定文件丢失。你知道吗

如果您必须建议更改逻辑或现有代码,请执行以下操作:所以。谢谢你知道吗


Tags: 文件ofpathinimporttxt文件夹os
1条回答
网友
1楼 · 发布于 2024-09-25 00:29:35

将形状列表转换为dict:

import os
import fiona
rootdir = r'C:\Users\user\Desktop\a' # path to your root directory you walk
sfiles = {} # a dictionary with all the .shp files
for entry in os.listdir(rootdir):
    dirpath = os.path.join(rootdir, entry)
    if os.path.isdir(dirpath): 
        for file in os.listdir(dirpath): # Get all files in the subdirectories
            if file.endswith('.shp'): # If it's an .shp.
                filepath = os.path.join(dirpath, file)
                sfiles[filepath[:-4]] = fiona.open(filepath)

然后你做一个动作格言如下:

action_dict = {'INT': 'intersection', 'ER': 'difference'}

后来在你的代码里

directory=input('Insert dir of the main folder')
with open(input()) as txtfile: #insert directory of txt
    x = txtfile.readlines()

results = []
for line in x:
    action, shape1, shape2 = line.split('_')  # here line is ER_ASTOM_ASTIK or whatever line in your txt file
    if shape1 in sfiles and shape2 in sfiles:
        results.append(gpd.overlay(sfiles[shape1], sfiles[shape2], how=action_dict[action]))

相关问题 更多 >