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

时间:2018-06-27 11:00:21

标签: python

我有一个类似于txt的txt,但有更多行。

我想询问包含子文件夹的主文件夹的目录,每个子文件夹在ASTIK.shp子文件夹中包含ASTIK,然后在{{1}中包含EAS.shp }子文件夹,然后是EAS

ASTOM.shp表示与此代码进行交集,在这种情况下,该代码应包含INTASTIK shapefile。

例如一行:

EAS

暗示:

INT_ASTIK_EAS  

然后转到另一行并“抓住”该行的含义,并在两个命名的shapefile之间执行擦除(差异)操作。

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

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

它应该执行:

ER_ASTOM_ASTIK

然后找到确切的文件并执行。我如何做到这一点而又不作很多条件和逐行处理:像

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

这将找到用户提供的路径中通常具有shps的目录:

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

,然后以某种方式 将txt中的单词与提到的文件连接到相应的计算(相交或相异)。

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

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))

我不认为唯一的方法是创建 If 'INT' in firstline of txt in directory and ASTOM and EAS: perform intersection between those. 条件的乱码,而这些条件可能永远不会有效。

我应该如何完成整个工作?

很有可能是txt中提到的文件丢失了。我很遗憾不提及它。它需要例外声明并声明该特定文件丢失。

如果您必须建议更改逻辑或现有代码,请这样做。

1 个答案:

答案 0 :(得分:0)

您将形状列表转换为字典:

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]))