使用Python覆盖文本文件中的特定行

问题描述 投票:0回答:2

我有一个异构的txt文件,我需要覆盖它中间的特定行。我试图用pandas函数来做这件事,但它只是覆盖了数据帧。使用csv我也没有成功。

这个想法是允许用户设置一些参数,然后保存:

import pandas as pd

file = r'\teste.txt'
col_names = ['Name', 'Elev.', 'MaxDepth', 'InitDepth', 'Shape', 'Curve Name/Params', 'Fevap', 'Psi', 'Ksat', 'IMD']
df = pd.read_csv(file, skiprows=54, skipfooter=79, header=None, names=col_names, delim_whitespace=True, index_col=0)
value1 = df.loc['J1']['Curve Name/Params']  
value2 = df.loc['J2']['Curve Name/Params']  
value3 = df.loc['J3']['Curve Name/Params']  
value4 = df.loc['J4']['Curve Name/Params']

df.at['J1', 'Curve Name/Params'] = input("Insert new area J1:")
df.at['J2', 'Curve Name/Params'] = input("Insert new area J2:")  
df.at['J3', 'Curve Name/Params'] = input("Insert new area J3:")  
df.at['J4', 'Curve Name/Params'] = input("Insert new area J4:")  
print(df[['Curve Name/Params']])
#save the parameters at the txt file

txt文件是水文模型(SWMM)的一个条目,它看起来像这样(我要覆盖的参数用4星****标记):

[TITLE]
";;Project Title/Notes"

[OPTIONS]
";;Option             Value"
FLOW_UNITS           CMS
INFILTRATION         CURVE_NUMBER
FLOW_ROUTING         DYNWAVE
LINK_OFFSETS         DEPTH
MIN_SLOPE            0
ALLOW_PONDING        NO
SKIP_STEADY_STATE    NO

START_DATE           07/23/2018
START_TIME           00:00:00
REPORT_START_DATE    07/23/2018
REPORT_START_TIME    00:00:00
END_DATE             07/23/2018
END_TIME             06:00:00
SWEEP_START          01/01
SWEEP_END            12/31
DRY_DAYS             0
REPORT_STEP          00:01:00
WET_STEP             00:05:00
DRY_STEP             01:00:00
ROUTING_STEP         0:00:30 

INERTIAL_DAMPING     PARTIAL
NORMAL_FLOW_LIMITED  BOTH
FORCE_MAIN_EQUATION  H-W
VARIABLE_STEP        0.75
LENGTHENING_STEP     0
MIN_SURFAREA         1.14
MAX_TRIALS           8
HEAD_TOLERANCE       0.0015
SYS_FLOW_TOL         5
LAT_FLOW_TOL         5
MINIMUM_STEP         0.5
THREADS              1

[EVAPORATION]
";;Data Source    Parameters"
";;-------------- ----------------"
CONSTANT         0.0
DRY_ONLY         NO

[OUTFALLS]
";;Name           Elevation  Type       Stage Data       Gated    Route To        "
";;-------------- ---------- ---------- ---------------- -------- ----------------"
OF1              996.1      FREE                        NO                       

[STORAGE]
";;Name           Elev.    MaxDepth   InitDepth  Shape      Curve Name/Params            N/A      Fevap    Psi      Ksat     IMD     "
";;-------------- -------- ---------- ----------- ---------- ---------------------------- -------- --------          -------- --------"
J2               999.1    1.5        0          FUNCTIONAL **10000**      0         0        0        0       
J1               1001     1.5        0          FUNCTIONAL **10000**      0         0        0        0       
J4               997.1    1.5        0          FUNCTIONAL **10000**      0         0        0        0       
J3               999      1.5        0          FUNCTIONAL **10000**      0         0        0        0       

[CONDUITS]
";;Name           From Node        To Node          Length     Roughness  InOffset   OutOffset  InitFlow   MaxFlow   "
";;-------------- ---------------- ---------------- ---------- ---------- ---------- ---------- ---------- ----------"
C1               J1               J3               100        0.013      0          1          0          0         
C2               J2               J4               100        0.013      0          1          0          0         
C3               J3               J4               100        0.013      0          0.9        0          0         
C4               J4               OF1              100        0.013      0          0          0          0         

[XSECTIONS]
";;Link           Shape        Geom1            Geom2      Geom3      Geom4      Barrels    Culvert   "
";;-------------- ------------ ---------------- ---------- ---------- ---------- ---------- ----------"
C1               CIRCULAR     0.5              0          0          0          1                    
C2               CIRCULAR     0.5              0          0          0          1                    
C3               CIRCULAR     0.6              0          0          0          1                    
C4               CIRCULAR     0.7              0          0          0          1                    

[INFLOWS]
";;Node           Constituent      Time Series      Type     Mfactor  Sfactor  Baseline Pattern"
";;-------------- ---------------- ---------------- -------- -------- -------- -------- --------"
J2               FLOW             TR20ANOS         FLOW     1.0      1.0              
J1               FLOW             TR20ANOS         FLOW     1.0      1.0              
J4               FLOW             TR20ANOS         FLOW     1.0      1.0              
J3               FLOW             TR20ANOS         FLOW     1.0      1.0              

[TIMESERIES]
";;Name           Date       Time       Value     "
";;-------------- ---------- ---------- ----------"
TR20ANOS                    0:00       0         
TR20ANOS                    0:01       0.063     
TR20ANOS                    0:02       0.126     
TR20ANOS                    0:03       0.190     
TR20ANOS                    0:04       0.253     
TR20ANOS                    0:05       0.316     
TR20ANOS                    0:06       0.379     
TR20ANOS                    0:07       0.358     
TR20ANOS                    0:08       0.337     
TR20ANOS                    0:09       0.316     
TR20ANOS                    0:10       0.295     
TR20ANOS                    0:11       0.274     
TR20ANOS                    0:12       0.253     
TR20ANOS                    0:13       0.232     
TR20ANOS                    0:14       0.211     
TR20ANOS                    0:15       0.190     
TR20ANOS                    0:16       0.168     
TR20ANOS                    0:17       0.147     
TR20ANOS                    0:18       0.126     
TR20ANOS                    0:19       0.105     
TR20ANOS                    0:20       0.084     
TR20ANOS                    0:21       0.063     
TR20ANOS                    0:22       0.042     
TR20ANOS                    0:23       0.021     
TR20ANOS                    0:24       0.000     

[REPORT]
";;Reporting Options"
INPUT      NO
CONTROLS   NO
SUBCATCHMENTS ALL
NODES ALL
LINKS ALL

[TAGS]

[MAP]
DIMENSIONS 0.000 0.000 10000.000 10000.000
Units      None

[COORDINATES]
";;Node           X-Coord            Y-Coord           "
";;-------------- ------------------ ------------------"
OF1              100.000            0.000             
J2               0.000              100.000           
J1               0.000              200.000           
J4               100.000            100.000           
J3               100.000            200.000           

[VERTICES]
";;Link           X-Coord            Y-Coord           "
";;-------------- ------------------ ------------------"

在此先感谢您的帮助。

python pandas overwrite
2个回答
2
投票

你可以在这里使用简单的文件。你只需要:

  • 打开文件和读取行
  • 使用正则表达式获取正确的行以检查星号或您想要匹配的任何内容
  • 相应地执行操作和覆盖参数
  • 写入文件

Code

我使用了您在data.txt中提供的数据并将结果保存在new.txt中。以下是我使用的代码。

import re

with open('data.txt', 'r') as infile,  open('new.txt', 'a') as outfile:
    for curr_line in infile:
        matchObj = re.match(r'[^*]+\*\*[^*]+\*\*[^*]+', curr_line, re.M | re.I)
        if matchObj:
            ## Perform some stuff and overwrite the row
            curr_line = '   Updated Row   '
        outfile.write(curr_line)

Result

这是我得到的输出

[TITLE]
";;Project Title/Notes"

[OPTIONS]
";;Option             Value"
FLOW_UNITS           CMS
INFILTRATION         CURVE_NUMBER
FLOW_ROUTING         DYNWAVE
LINK_OFFSETS         DEPTH
MIN_SLOPE            0
ALLOW_PONDING        NO
SKIP_STEADY_STATE    NO

START_DATE           07/23/2018
START_TIME           00:00:00
REPORT_START_DATE    07/23/2018
REPORT_START_TIME    00:00:00
END_DATE             07/23/2018
END_TIME             06:00:00
SWEEP_START          01/01
SWEEP_END            12/31
DRY_DAYS             0
REPORT_STEP          00:01:00
WET_STEP             00:05:00
DRY_STEP             01:00:00
ROUTING_STEP         0:00:30

INERTIAL_DAMPING     PARTIAL
NORMAL_FLOW_LIMITED  BOTH
FORCE_MAIN_EQUATION  H-W
VARIABLE_STEP        0.75
LENGTHENING_STEP     0
MIN_SURFAREA         1.14
MAX_TRIALS           8
HEAD_TOLERANCE       0.0015
SYS_FLOW_TOL         5
LAT_FLOW_TOL         5
MINIMUM_STEP         0.5
THREADS              1

[EVAPORATION]
";;Data Source    Parameters"
";;-------------- ----------------"
CONSTANT         0.0
DRY_ONLY         NO

[OUTFALLS]
";;Name           Elevation  Type       Stage Data       Gated    Route To        "
";;-------------- ---------- ---------- ---------------- -------- ----------------"
OF1              996.1      FREE                        NO

[STORAGE]
";;Name           Elev.    MaxDepth   InitDepth  Shape      Curve Name/Params            N/A      Fevap    Psi      Ksat     IMD     "
";;-------------- -------- ---------- ----------- ---------- ---------------------------- -------- --------          -------- --------"
   Updated Row      Updated Row      Updated Row      Updated Row   
[CONDUITS]
";;Name           From Node        To Node          Length     Roughness  InOffset   OutOffset  InitFlow   MaxFlow   "
";;-------------- ---------------- ---------------- ---------- ---------- ---------- ---------- ---------- ----------"
C1               J1               J3               100        0.013      0          1          0          0
C2               J2               J4               100        0.013      0          1          0          0
C3               J3               J4               100        0.013      0          0.9        0          0
C4               J4               OF1              100        0.013      0          0          0          0

[XSECTIONS]
";;Link           Shape        Geom1            Geom2      Geom3      Geom4      Barrels    Culvert   "
";;-------------- ------------ ---------------- ---------- ---------- ---------- ---------- ----------"
C1               CIRCULAR     0.5              0          0          0          1
C2               CIRCULAR     0.5              0          0          0          1
C3               CIRCULAR     0.6              0          0          0          1
C4               CIRCULAR     0.7              0          0          0          1

[INFLOWS]
";;Node           Constituent      Time Series      Type     Mfactor  Sfactor  Baseline Pattern"
";;-------------- ---------------- ---------------- -------- -------- -------- -------- --------"
J2               FLOW             TR20ANOS         FLOW     1.0      1.0
J1               FLOW             TR20ANOS         FLOW     1.0      1.0
J4               FLOW             TR20ANOS         FLOW     1.0      1.0
J3               FLOW             TR20ANOS         FLOW     1.0      1.0

[TIMESERIES]
";;Name           Date       Time       Value     "
";;-------------- ---------- ---------- ----------"
TR20ANOS                    0:00       0
TR20ANOS                    0:01       0.063
TR20ANOS                    0:02       0.126
TR20ANOS                    0:03       0.190
TR20ANOS                    0:04       0.253
TR20ANOS                    0:05       0.316
TR20ANOS                    0:06       0.379
TR20ANOS                    0:07       0.358
TR20ANOS                    0:08       0.337
TR20ANOS                    0:09       0.316
TR20ANOS                    0:10       0.295
TR20ANOS                    0:11       0.274
TR20ANOS                    0:12       0.253
TR20ANOS                    0:13       0.232
TR20ANOS                    0:14       0.211
TR20ANOS                    0:15       0.190
TR20ANOS                    0:16       0.168
TR20ANOS                    0:17       0.147
TR20ANOS                    0:18       0.126
TR20ANOS                    0:19       0.105
TR20ANOS                    0:20       0.084
TR20ANOS                    0:21       0.063
TR20ANOS                    0:22       0.042
TR20ANOS                    0:23       0.021
TR20ANOS                    0:24       0.000

[REPORT]
";;Reporting Options"
INPUT      NO
CONTROLS   NO
SUBCATCHMENTS ALL
NODES ALL
LINKS ALL

[TAGS]

[MAP]
DIMENSIONS 0.000 0.000 10000.000 10000.000
Units      None

[COORDINATES]
";;Node           X-Coord            Y-Coord           "
";;-------------- ------------------ ------------------"
OF1              100.000            0.000
J2               0.000              100.000
J1               0.000              200.000
J4               100.000            100.000
J3               100.000            200.000

[VERTICES]
";;Link           X-Coord            Y-Coord           "
";;-------------- ------------------ ------------------"

0
投票

也许直截了当的方法适合你?

with open('test.txt') as inp:
  with open('result.txt') as outp:
    for line in inp:
      if line:  # skip processing empty lines
        items = line.split()
        if items[0] == 'J1':
          items[123] = input('blahblah')
        line = ' '.join(items)
      outp.write(line)

我尝试使代码变得简单,我看到的唯一问题是它在编辑后不会保留行中的空格量。如果重要,应该更新代码。

© www.soinside.com 2019 - 2024. All rights reserved.