读取文件并将结果存储在字符串中后没有换行符

No new line character after reading a file and storing result in a string

在我从文件中读取并将结果存储到字符串中后,有没有办法检测换行符?这是代码:

with open("text.txt") as file:
    content_string = file.read()
    file.close()

re.search("\n", content_string)

content_string 看起来像这样:

Hello world!
Hello WORLD!!!!!

我想提取第一行后的换行符"Hello world!"。这个角色当时是否存在?

根据 Jongware 评论,您执行的正则表达式搜索找到换行符。您只需要使用该结果即可。

来自re module documentation

re.search(模式、字符串、标志=0)

Scan through string looking for the first location where the regular expression pattern produces a match, and return a corresponding MatchObject instance. Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.

就代码而言,检查转化为:

with open("text.txt") as file:
    content_string = file.read()
    file.close()

m = re.search("\n", content_string)
if m:
    print "Found a newline"
else:
    print "No newline found"

现在,您的文件很可能包含“\r”而不是“\n”:它们打印出来的内容可能相同,但正则表达式不匹配。在这种情况下,也请尝试此测试,替换代码中的正确行:

m = re.search("\n", content_string)

与:

m = re.search("[\r\n]", content_string)

哪个会寻找。

How about if I have more lines, and I want to detect the first newline? For some reason, in my text it won't detect it.

with open("text.txt") as f:
    first_line = f.readline()
    print(first_line)

Is there a way to detect the new line character after I've read from a file and stored the results into a string?

如果我没理解错的话,您想将多行连接成一个字符串。 输入:

Hello world!
Hello WORLD!!!!!

test.py:

result = []
with open("text.txt", "rb") as inputs:
    for line in inputs:
        result.append(line.strip())  # strip() removes newline charactor

print " ".join([x for x in result])

输出:

Hello world! Hello WORLD!!!!!