【问题标题】:Add 1 word after readlines()在 readlines() 之后添加 1 个单词
【发布时间】:2020-04-21 09:50:21
【问题描述】:

我还在学习python,对函数readlines()有疑问以下是我脚本的一部分:

f = open("demofile.txt", "r")
text = "".join(f.readlines())
print(text)

demofile.txt 包含:

This is the first line
This is the second line
This is the third line

现在我想在其中添加一个单词,所以我得到:

This is the first line
This is the second line
This is the third line
Example

我想到了一些简单的方法:

f = open("demofile.txt", "r")
text = "".join(f.readlines())."Example"
print(text)

但这不起作用(当然)我用谷歌搜索并环顾四周,但实际上并没有很好的关键字来搜索这个问题。希望有人能指出我正确的方向。

【问题讨论】:

    标签: python list readlines


    【解决方案1】:

    .readlines()返回list你可以append()给它:

    with open("demofile.txt") as txt:
        lines = txt.readlines()
        lines.append("Example")
        text = "".join(lines)
        print(text)
    

    或者你可以解压文件对象txt,因为它是一个指向新list 的迭代器,带有你想要添加的单词:

    with open("demofile.txt") as txt:
        text = "".join([*txt, "Example"])
        print(text)
    

    【讨论】:

    • 注意:在拆包的情况下,你根本不需要.readlines();文件对象是一个可以解压的迭代器,所以text = "".join([*txt, "Example"]) 工作得很好,只需要一个临时的list,而不是两个。
    【解决方案2】:

    首先,python 中的open 函数默认以读取模式打开文件。因此,您无需在打开文件时指定模式r。其次,您应该始终在完成文件后关闭它。 python 中的with 语句会为您处理这个问题。此外,不要使用.Example 添加到字符串的末尾,而应使用python 中的连接运算符添加换行符\n 和字符串Example

    with open("demofile.txt") as f:
        text = "".join(f.readlines()) + "\nExample"
        print(text)
    

    【讨论】:

      【解决方案3】:

      这应该对您有所帮助。在处理文件时。始终建议使用with open('filename','r') as f 而不是f=open('filename','r')。在文件打开期间使用ContextManager 的想法是,无论一切正常还是引发任何异常,该文件都将在任何情况下打开。而且您不需要显式关闭文件,即f.close()

      end_text='Example'
      with open('test.txt','r') as f:
          text=''.join(f.readlines())+'\n'+end_text
          print(text)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-17
        • 2017-03-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多