【问题标题】:Python Writing a text at the end of each sentence in the filePython 在文件中每个句子的末尾写一段文字
【发布时间】:2020-04-09 15:57:26
【问题描述】:
f=open('file.txt', 'a', 
encoding='utf-8')
f.write('+1/n')
f.write('+2/n')


f.close()

在file.txt中,结果是

Line 1
Line 2
+1
+2

我想要这个

Line 1+1
Line 2+2

如何在每个句子的末尾写一段文字?

【问题讨论】:

标签: python file


【解决方案1】:

您可以打开文件并阅读带有readlines() 的行。然后回到开头并写下你添加的行。比如:

with open(path,'r+') as f:
    lines = f.readlines()
    f.seek(0)
    for i, line in enumerate(map(str.strip, lines)):
        f.write(f'{line}+{i+1}\n')

【讨论】:

    【解决方案2】:

    试试这个:

    with open('file.txt','r', encoding='utf-8') as fr:
        lines = fr.readlines()
    
    with open('file.txt','w', encoding='utf-8') as fw:
        for i,l in enumerate(lines):
            fw.write(f"l+{i+1}\n")
    

    【讨论】:

      【解决方案3】:

      原始文本文件:

      line 1
      line 2
      line 3
      line 4
      

      代码:

      with open("file.txt", "r") as f:
          lines = f.readlines()
          with open("file.txt", "w") as out_f:
              for i, j in enumerate(lines):  # i represents the index of the line starting at 0. j represents the line itself
                  out_f.write(j.strip("\n") + f"+{i + 1}\n")
      

      输出后的文件:

      line 1+1
      line 2+2
      line 3+3
      line 4+4
      

      【讨论】:

        猜你喜欢
        • 2014-02-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-10
        • 2015-02-13
        • 1970-01-01
        • 2018-11-07
        • 1970-01-01
        相关资源
        最近更新 更多