【问题标题】:How to add or replace some string at a particular column position in a text file如何在文本文件的特定列位置添加或替换某些字符串
【发布时间】:2014-02-03 10:02:29
【问题描述】:

如何在文本文件的特定列位置添加或替换某些字符串: 例如,我在下面给出的特定文件示例中有一句话:

Roxila almost lost
Roxila almost lost
Roxila almost lost
Roxila almost lost
Roxila almost lost

"enumerate()" 给出了类似的东西

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
R o x i l a   a l m  o  s  t     l  o  s  t 

现在我想改变索引“6”,它是每行带有“*”的“空格”。像这样:

Roxila*almost lost

我怎样才能用 python 做到这一点。请帮忙

【问题讨论】:

    标签: python string file


    【解决方案1】:

    您可以使用切片获取新字符串和fileinput 模块来更新现有文件:

    切片演示:

    >>> s = "Roxila almost lost"
    'Roxila almost lost'
    >>> s [:6] + '*' + s[7:]
    'Roxila*almost lost'
    

    更新文件:

    import fileinput
    for line in fileinput.input('foo.txt', inplace=True):
        print line[:6] + '*' + line[7:],
    

    【讨论】:

      【解决方案2】:

      如果你的第一个字符串发生变化,这意味着长度,在这种情况下切片将不起作用:

      最好用这种方式:

      >>> s.split(' ')
      ['Roxila', 'almost', 'lost']
      >>> p = s.split(' ')
      >>> p[0]+'*'+' '.join(p[1:])
      'Roxila*almost lost'
      >>>
      

      【讨论】:

        【解决方案3】:
        for line in f:
           line = line.rstrip()
           newline = line[:6] + '*' + line[7:]
           print newline
        

        【讨论】:

          【解决方案4】:

          另一种方法,使用替换

          with open("yourfile.txt", "r") as file:
              lines = file.read().split("\n")
              newlines = []
              for line in lines:
                  newline = line.replace(" ", "*", 1)
                  newlines.append(newline)
          
          with open("newfile.txt", "w") as newfile:    
              newfile.write("\n".join(newlines))
          

          【讨论】:

            猜你喜欢
            • 2017-06-13
            • 2019-11-17
            • 2017-08-30
            • 1970-01-01
            • 2015-06-16
            • 2011-01-15
            • 1970-01-01
            • 1970-01-01
            • 2019-04-07
            相关资源
            最近更新 更多