【问题标题】:How do i remove a character from each line of a text file using python? [duplicate]如何使用 python 从文本文件的每一行中删除一个字符? [复制]
【发布时间】:2019-02-05 18:35:08
【问题描述】:

我想删除文本文件每一行末尾的 \n,因为我需要将每一行作为单独的列表项放在列表中。

with open("PythonTestFile.txt", "rt") as openfile:

    for line in openfile:
        new_list = []

        new_list.append(line)

        print(new_list)

这就是我得到的

['1) This is just an empty file.\n']

['2) This is the second line.\n']

['3) Third one.\n']

['4) Fourth one.\n']

['5) Fifth one.\n']

This is what I want

['1) This is just an empty file.']

['2) This is the second line.']

['3) Third one.']

['4) Fourth one.']

['5) Fifth one.']

【问题讨论】:

  • new_list.append(line.strip('\n')).

标签: python list text-files


【解决方案1】:

尝试使用string.strip()

with open("PythonTestFile.txt", "rt") as openfile:
    new_list = []
    for line in openfile:
        new_list.append(line.rstrip('\n'))

    print(new_list)

【讨论】:

  • 使用不带参数的.strip 会删除空白字符,而不仅仅是换行符,因此例如,如果行尾是空格,它也会被丢弃。最好使用.strip('\n'),它只会丢弃换行符。
  • @Daweo 好点;编辑我的答案以使用rstrip('\n')
  • a@Daweo 和 @cmac 非常感谢你们
【解决方案2】:
line = line.rstrip('\n')

这将取消行尾的换行符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-27
    • 1970-01-01
    • 2015-11-19
    • 2011-10-01
    • 2018-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多