如何使用python从文本文件的每一行中删除字符?

时间:2019-02-05 18:35:08

标签: python list text-files

我想删除文本文件每一行末尾的\ 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.']

2 个答案:

答案 0 :(得分:1)

line = line.rstrip('\n')

这会将换行符放在行尾。

答案 1 :(得分: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)