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

时间:2018-12-21 14:48:18

标签: python pandas overwrite

我有一个异构的txt文件,我需要覆盖其中的特定行。我尝试使用熊猫函数 at 来做到这一点,但是它只是覆盖了数据框。使用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           "
";;-------------- ------------------ ------------------"

在此先感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

您可以在此处使用简单的归档。您只需要:

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

代码

我使用了您在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)

结果

这是我得到的输出

[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           "
";;-------------- ------------------ ------------------"

答案 1 :(得分: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)

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