Python:读取行并修改它(如果需要)

2024-04-26 02:49:48 发布

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

假设我有一个文件Example.txt,如下所示:

alpha_1 = 10

%alpha_2 = 20

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

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

  2. 执行1中的任务。独立于行顺序

  3. 保留文件的其余部分Example.txt

我写的文件是:

^{pr2}$

到目前为止,输出是相同的Example.txt,在原始行(%alpha1 =, 10)下一行alpha1 = 10。在

谢谢大家


Tags: 文件alphatxt脚本参数顺序example符号
1条回答
网友
1楼 · 发布于 2024-04-26 02:49:48

过了一会儿我找到了解决办法。所有事情都可以很容易地完成,把所有的东西都写在另一个文件中,并在最后替换它。在

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

相关问题 更多 >

    热门问题