【问题标题】:Problem with replacing a word in a file, using Python使用Python替换文件中的单词的问题
【发布时间】:2011-01-17 06:58:43
【问题描述】:

我有一个包含如下数据的 .txt 文件:

1,Rent1,Expense,16/02/2010,1,4000,4000  
1,Car Loan1,Expense,16/02/2010,2,4500,9000  
1,Flat Loan1,Expense,16/02/2010,2,4000,8000  
0,Rent2,Expense,16/02/2010,1,4000,4000  
0,Car Loan2,Expense,16/02/2010,2,4500,9000  
0,Flat Loan2,Expense,16/02/2010,2,4000,8000 

我想替换第一项。如果是 1,意味着它应该保持不变,但如果是 0,则意味着我想将其更改为 1。所以我尝试使用以下代码:

import fileinput
for line in fileinput.FileInput("sample.txt",inplace=1):
    s=line.split(",")
    print a
    print ','.join(s)

但在成功执行程序后,我的 .txt 文件如下所示:

1,Rent1,Expense,16/02/2010,1,4000,4000

1,Car Loan1,Expense,16/02/2010,2,4500,9000

1,Flat Loan1,Expense,16/02/2010,2,4000,8000

0,Rent2,Expense,16/02/2010,1,4000,4000

0,Car Loan2,Expense,16/02/2010,2,4500,9000

0,Flat Loan2,Expense,16/02/2010,2,4000,8000

现在我想删除空行。是否有可能,或者有没有其他方法可以替换 0?

【问题讨论】:

标签: python file replace


【解决方案1】:

在打印之前使用rstrip 删除尾随的新行,或者使用sys.stdout.write 而不是print

另外,如果只需要修改第一个元素,则不需要将整行拆分后再加入。您只需要在第一个逗号处拆分:

line.split(',', 1)

如果您想要更好的性能,您也可以直接测试line[0] 的值。

【讨论】:

    【解决方案2】:

    print 在输入之后添加一个额外的换行符,而您已经有一个换行符。您应该去掉现有的换行符 (line.rstrip("\n")) 或改用 sys.stdout.write()

    【讨论】:

      【解决方案3】:
      import fileinput
      import re
      p = re.compile(r'^0,')
      for line in fileinput.FileInput("sample.txt",inplace=1):
          print p.sub('1,', line.strip())
      

      您拥有的现有代码实际上并没有像您想要的那样更改行;如果a 没有真正定义,print a 不会做任何事情!所以你最终只打印一个空行(print a 位)然后打印现有行,因此你得到一个除了添加一些空行之外没有改变的文件。

      【讨论】:

      • +1:只需将print re.sub(r'^0,', '1,', line) 替换为print re.sub(r'^0,', '1,', line.strip()),这样可以去掉空行。
      • 一开始就不需要条带;只需在原始文件而不是空白文件上运行它。
      • 在 Win32 上使用 Python26,如果不使用 strip() 或 rstrip(),则会在原始文件中出现空行
      【解决方案4】:
      fixed = []
      for l in file('sample.txt'):
          parts = l.split(',',1)
          if(parts[0] == '0'):
              # not sure what you want to do here, but you want to "change this" number to 1?
              parts[0] = 1
          fixed.append(parts.join(','))
      outp = file('sample.txt','w')
      for f in fixed:
          outp.write(f)
      outp.close()
      

      这是未经测试的,但它应该可以让你大部分时间到达那里。 祝你好运

      【讨论】:

        【解决方案5】:
        import fileinput
        for line in fileinput.FileInput("sample.txt",inplace=1):
            s=line.rstrip().split(",")
            print a
            print ','.join(s)
        

        【讨论】:

          【解决方案6】:

          您必须在 print 的末尾使用逗号,这样它就不会添加换行符。像这样:

          print "Hello",
          

          这是我想出的:

          input = open('file.txt', 'r')
          output = open('output.txt', 'w')
          for line in input:
              values = line.split(',')
              if (values[0] == '0'):
                  values[0] = '1'
              output.write(','.join(values))
          

          如果您想要更好的 csv 处理库,您可能希望使用 this 而不是 split。

          【讨论】:

            【解决方案7】:

            最简洁的方法是使用 CSV 解析器:

            import fileinput
            import csv 
            
            f = fileinput.FileInput("test.txt",inplace=1)
            fichiercsv = csv.reader(f, delimiter=',')
            
            for line in fichiercsv:
                line[0] = "1"
                print ",".join(line)
            

            【讨论】:

              猜你喜欢
              • 2019-09-04
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2013-05-05
              • 1970-01-01
              • 1970-01-01
              • 2015-03-02
              • 1970-01-01
              相关资源
              最近更新 更多