简体   繁体   English

读取文件中以\\ n结尾的行

[英]Reading lines in a file that end with \n

When I do 当我做

f = open("test.txt","r")
s = f.readline()
l = s.split[' ']

in which the input file has the content 2 3\\n . 其中输入文件的内容为2 3\\n s has the value ['2', '3\\n'] . s的值为['2', '3\\n'] Is there a way to tell python that each line ends with a \\n and therefore it should not read it? 有没有办法告诉python每行以\\n结尾,因此不应该读取它?

Contents of file: 文件内容:

3 2\n
#1###2#\n
****#**\n
##*###*\n
#******\n
#*#O##*\n

I will do other operations for the other lines. 我将对其他行执行其他操作。 But I still need to get rid of \\n 但是我仍然需要摆脱\\n

The caveat here is that except for the literal '\\n' there is also an actual \\n at the end of each line (except for the last line, which only has the literal '\\n' ): 需要注意的是,除了文字'\\n'之外,每行的末尾还有一个实际的\\n (最后一行除外,后者仅包含文字'\\n' ):

with open('test.txt') as f:
    print(f.readlines())
# ['3 2\\n\n', '#1###2#\\n\n', '****#**\\n\n', '##*###*\\n\n', '#******\\n\n', '#*#O##*\\n']

You need to call .strip with both the literal '\\n' and the actual \\n : 您需要同时使用文字'\\n'和实际的\\n来调用.strip

with open('test.txt') as f:
    lines = [line.strip('\\n\n') for line in f]

print(lines)
# ['3 2', '#1###2#', '****#**', '##*###*', '#******', '#*#O##*']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM