【问题标题】:How can i write to a txt file with multiple lines?如何写入包含多行的 txt 文件?
【发布时间】:2013-05-15 13:03:53
【问题描述】:

我进行了一项在线调查,并在一个 txt 文件中记录了所有输入。

以下是两个问题,每次有人回答一个问题,我都想将答案附加到对应的问题中。

到目前为止,我的 txt 文件中只有这些:

0,在 1-5 的范围内,你今天感觉如何?,3,5,4,5,4,3,

1、哪些活动可以改善心情?,吃,睡,喝,说话,看电视,

我的问题是:如何使用 python 将数据附加到文件的第一行而不是第二行?

如果我这样做:

f= open ('results.txt','a')
f.write ('5')
f.close ()

它会将“5”附加到第二行,但我希望将该结果添加到第一个问题中。

【问题讨论】:

标签: python file append lines


【解决方案1】:

您不能在文件中间插入数据。你必须重写文件。

【讨论】:

    【解决方案2】:

    你可以试试这个方法:

    >>> d = open("asd")
    >>> dl = d.readlines()
    >>> d.close()
    >>> a = open("asd", 'w')
    >>> dl = dl[:1] + ["newText"] + dl[1:]
    >>> a.write("\n".join(dl))
    >>> a.close()
    

    【讨论】:

      【解决方案3】:

      您可以使用模式rb+在文件中添加一些内容

      import re
      
      ss = '''
      0, On a scale of 1-5, how are you feeling today?,3,5,4,5,4,3,
      
      1, What activities can improve your mood?,eat,sleep,drink,talk,tv,
      
      2, What is worse condition for you?,humidity,dry,cold,heat,
      '''
      
      # not needed for you
      with open('tryy.txt','w') as f:
          f.write(ss)
      
      
      # your code
      line_appendenda = 1
      x_to_append = 'weather'
      
      with open('tryy.txt','rb+') as g:
          content = g.read()
          # at this stage, pointer g is at the end of the file
          m = re.search('^%d,[^\n]+$(.+)\Z' % line_appendenda,
                        content,
                        re.MULTILINE|re.DOTALL)
          # (.+) defines group 1
          # thanks to DOTALL, the dot matches every character
          # presence of \Z asserts that group 1 spans until the
          # very end of the file's content
          # $ in ther pattern signals the start of group 1
          g.seek(m.start(1))
          # pointer g is moved back at the beginning of group 1
          g.write(x_to_append)
          g.write(m.group(1))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-11-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-23
        • 2017-02-25
        相关资源
        最近更新 更多