简体   繁体   中英

Concatenate lines together if they are not emty in a file

I have a file where some sentence are spread over multiple lines. For example:

1:1 This is a simple sentence
[NEWLINE]
1:2 This line is spread over 
multiple lines and it goes on
and on.
[NEWLINE]
1:3 This is a line spread over
two lines
[NEWLINE]

So I want it to look like this

1:1 This is a simple sentence
[NEWLINE]
1:2 This line is spread over multiple lines and it goes on and on.
[NEWLINE]
1:3 This is a line spread over two lines

Some lines a spread over 2 or 3 or 4 lines. If there follows al line which is not an new line it should be merged into one single line. I would like to overwrite the given file of to make an new file.

I've tried it with a while loop but without succes.

input = open(file, "r")
zin = ""
lines = input.readlines()
#Makes array with the lines
for i in lines:
    while i != "\n"
        zin += i
.....

But this creates a infinite loop.

You should not be nesting for and while loops in your use case. What happens in your code is that a line is assigned to the variable i by the for loop, but it isn't being modified by the nested while loop, so if the while clause is True , then it will remain that way and without a breaking condition, you end up with an infinite loop.

A solution might look like this:

single_lines = []
current = []

for i in lines:
    i = i.strip()
    if i:
        current.append(i)
    else:
        if not current:
            continue  # treat multiple blank lines as one
        single_lines.append(' '.join(current))
        current = []
else:
    if current:
        # collect the last line if the file doesn't end with a blank line
        single_lines.append(' '.join(current))

Good ways of overwriting the input file would be to either collect all output in memory, close the file after reading it out and reopen it for writing, or to write to another file while reading the input and renaming the second one to overwrite the first after closing both.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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