简体   繁体   English

以“&”作为分隔符读取多行文件

[英]Reading a multiline file with “&” as separator

I have a file which contains the following content:我有一个包含以下内容的文件:

This is the first line.
&
This is the second line
but without separator.
&
This is the third line.
...

Each line terminates with a \n .每行以\n结尾。 I want to convert this file input into the following list: ['This is the first line.', 'This is the second line but without separator.', 'This is the third line.', ...]我想将此文件输入转换为以下列表: ['This is the first line.', 'This is the second line but without separator.', 'This is the third line.', ...]

My actual code looks like:我的实际代码如下所示:

file = open("/path/to/file", "r")
list = [line.rstrip() for line in file if not line.rstrip() is "&"]

The problem is that the multi line section gets separated in the list but I want it togehter with or without a \n in it.问题是多行部分在列表中被分开,但我希望它与或不包含\n一起。

I hope someone can give me a hint.我希望有人能给我一个提示。 Thanks!谢谢!

How about read all the lines and join them as a single string, then use String.split("&")如何读取所有行并将它们作为单个字符串连接,然后使用 String.split("&")

with open("test.txt") as file:
    lines = file.read()

print(lines.split("&"))
# to remove the \n
print(lines.replace("\n", "").split("&"))

Here is a working example.这是一个工作示例。 You already know how to read the file, here is how you might parse the contents.您已经知道如何读取文件,以下是解析内容的方法。

file_contents = """This is the first line.
&
This is the second line
but without separator.
&
This is the third line."""

all_lines = []
for l in file_contents.split('&'):
    all_lines.append(" ".join(l.split('\n')).rstrip())

print(all_lines)

Prints:印刷:

['This is the first line.', ' This is the second line but without separator.', ' This is the third line.']

just split the whole file by & and remove whitespace (assuming that they should just be separated by & )只需用&分割整个文件并删除空格(假设它们应该用&分隔)

l = [s.strip().replace('\n', ' ') for s in file.read().split('&')]

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

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