【问题标题】:Python: read line and modify it (if needed)Python:读取行并修改它(如果需要)
【发布时间】:2018-07-31 03:10:31
【问题描述】:

假设我有一个像这样的文件Example.txt

alpha_1 = 10

%alpha_2 = 20

现在,我想要一个执行这些任务的 python 脚本:

  1. 如果包含alpha_1参数的行没有注释(%符号),重写添加%的行,就像alpha_2一样

  2. 执行 1. 中的任务,独立于生产线顺序

  3. 保持文件的其余部分保持不变Example.txt

我写的文件是:

with open('Example.txt', 'r+') as config:
      while 1:
        line = config.readline()
        if not line:
           break

    # remove line returns
    line = line.strip('\r\n')
    # make sure it has useful data
    if (not "=" in line) or (line[0] == '%'):
      continue
    # split across equal sign
    line = line.split("=",1)
    this_param = line[0].strip()
    this_value = line[1].strip()

    for case in switch(this_param):    

       if case("alpha1"):
          string = ('% alpha1 =', this_value )
          s = str(string)
          config.write(s)

到目前为止,输出与Example.txt 相同,但在原行alpha1 = 10 下方又增加了一行(%alpha1 =, 10)

谢谢大家

【问题讨论】:

  • 欢迎来到 Stack Overflow。请使用tour 并阅读有关How to Ask 的信息。除了要求我们编写它之外,您的问题中没有 Python。我们在这里帮助您编写更好的 Python,但您至少需要开始。看看fileinput 模块函数input 和参数inplace=True 对于初学者。

标签: python formatting overwrite file-writing


【解决方案1】:

一段时间后我找到了解决方案。一切都可以轻松完成,将所有内容写入另一个文件并在最后替换它。

configfile2 = open('Example.txt' + '_temp',"w")
    with open('Example.txt', 'r') as configfile:
      while 1:          
       line = configfile.readline()
       string = line
       if not line:
        break

       # remove line returns
       line = line.strip('\r\n')
       # make sure it has useful data
       if (not "=" in line) or (line[0] == '%'):  
         configfile2.write(string)
       else: 
         # split across equal sign
         line = line.split("=",1)
         this_param = line[0].strip()
         this_value = line[1].strip()

         #float values
         if this_param == "alpha1":
           stringalt = '% alpha1 = '+ this_value + '   \r\n'
           configfile2.write(stringalt)                            
         else:
           configfile2.write(string) 

    configfile.close()    
    configfile2.close()
    # the file is now replaced
    os.remove('Example.txt' )
    os.rename('Example.txt' + '_temp','Example.txt' )

【讨论】:

    猜你喜欢
    • 2014-01-28
    • 1970-01-01
    • 1970-01-01
    • 2022-12-10
    • 2019-02-08
    • 2021-08-01
    • 2021-02-09
    • 2016-01-16
    相关资源
    最近更新 更多