Jeril
Jeril

Reputation: 8521

Python - separating individual lines in a paragraph from a text file

I have a text file which contains the following paragraph:

The above with statement will automatically close the file after the nested block of code. The above with statement will automatically close the file after the nested block of code. The above with statement will automatically close the file after the nested block of code.
The above with statement will automatically close the file after the nested block of code without.

Now, I would like to modify the file by separating the individual lines for the paragraph, and save it in the same text file as the following:

The above with statement will automatically close the file after the nested block of code.
The above with statement will automatically close the file after the nested block of code.
The above with statement will automatically close the file after the nested block of code.
The above with statement will automatically close the file after the nested block of code without.

I was able to do it, but it was bit complicated. My code is as follows:

try-1

file = open("file_path")
content = file.read()
file.close()
file = open("file_path", 'w')
a = content.replace('. ', '.\n')
file.write(a)
file.close()

try-2

file = open("file_path")
contents = file.readlines()
file.close()
b = []
for line in contents:
    if not line.strip():
        continue
    else:
        b.append(line)
b = "".join(b)
file = open("file_path", 'w')
file.write(b)
file.close()

I opened the file twice to read and twice to write, is there any better way to separate the line from a paragraph from a text file, and writing it to the same text file?

Upvotes: 0

Views: 1927

Answers (2)

arodriguezdonaire
arodriguezdonaire

Reputation: 5563

You can do:

with open('filepath', 'r') as contents, open('filepath', 'w') as file:
    contents = contents.read()
    lines = contents.split('. ')
    for index, line in enumerate(lines):
        if index != len(lines) - 1:
            file.write(line + '.\n')
        else:
            file.write(line + '.')

Upvotes: 5

Anton Protopopov
Anton Protopopov

Reputation: 31672

You can use seek method of files to jump in current file:

f.seek(offset, from_what)

And if you want to use file for write and read use option r+:

file = open("file_path", 'r+')

You also can skip step with readlines and use file iteration. Code should be:

file = open("file_path", "r+")
content = file.read()
a = content.replace('. ', '.\n')
file.seek(0)
file.write(a)

file.seek(0)

b = []
for line in file:
    if not line.strip():
        continue
    else:
        b.append(line)
b = "".join(b)
file.seek(0)
file.write(b)
file.close()

Upvotes: 1

Related Questions