如何删除从使用python的文本文件的每一行的文字? [重复]

问题描述 投票:0回答:2

这个问题已经在这里有一个答案:

我想删除这是在一个文本文件中的每一行的结束,因为我需要把每行列表中的一个单独的列表项\ 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.']
python list text-files
2个回答
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)

1
投票
line = line.rstrip('\n')

这将需要换行字符在该行离结束。

© www.soinside.com 2019 - 2024. All rights reserved.