Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用python从文本文件的每行中删除一个字符?_Python_List_Text Files - Fatal编程技术网

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

如何使用python从文本文件的每行中删除一个字符?,python,list,text-files,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

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


这将删除行尾的换行符。

尝试使用
string.strip()


尝试使用
string.strip()


new\u list.append(line.strip('\n'))
new\u list.append(line.strip('\n'))
。使用
.strip
不带参数删除空格字符,而不仅仅是换行符,因此,例如,如果行尾是空格,它也将被丢弃。最好使用
.strip('\n')
,它只会丢弃换行符。@Daweo good point;编辑我的答案以使用
rstrip('\n')
a@Daweo和@cmac thanky u soo much guysing
。strip
无参数删除空白字符,而不仅仅是换行符,因此,例如,如果行尾是空格,它也将被丢弃。最好使用
.strip('\n')
,它只会丢弃换行符。@Daweo good point;编辑我的答案以使用
rstrip('\n')
a@Daweo还有@cmac非常感谢你们
line = line.rstrip('\n')
with open("PythonTestFile.txt", "rt") as openfile:
    new_list = []
    for line in openfile:
        new_list.append(line.rstrip('\n'))

    print(new_list)