0

I would like to make a newline after a dot in a file.

For example:

Hello. I am damn cool. Lol

Output:

Hello.
I am damn cool.
Lol

I tried it like that, but somehow it's not working:

f2 = open(path, "w+")
    for line in f2.readlines():
        f2.write("\n".join(line))
    f2.close()

Could your help me there?

I want not just a newline, I want a newline after every dot in a single file. It should iterate through the whole file and make newlines after every single dot.

Thank you in advance!

Lucas
  • 154
  • 1
  • 12
  • Possible duplicate of [writing string to a file on a new line every time?](https://stackoverflow.com/questions/2918362/writing-string-to-a-file-on-a-new-line-every-time) – alex Oct 12 '17 at 12:59
  • @Chris_Rands this can't work.. you just wrote a newline into file. I want a newline after a dot. Not just a newline into the file somewhere – Lucas Oct 12 '17 at 12:59
  • Learn about `str.split()`; you need to actually split your string into a list of substrings ending with `.`, then print that list. – Błotosmętek Oct 12 '17 at 13:00
  • @Błotosmętek Yeah, but then the other words get lost. – Lucas Oct 12 '17 at 13:01
  • To be clear, you want to replace the pattern of a dot followed by whitespace with a newline? Replacing just the dots, your output lines would start with a space. – Izaak van Dongen Oct 12 '17 at 13:02

2 Answers2

4

This should be enough to do the trick:

with open('file.txt', 'r') as f:
    contents = f.read()

with open('file.txt', 'w') as f:
    f.write(contents.replace('. ', '.\n'))
adder
  • 3,512
  • 1
  • 16
  • 28
2

You could split your string based on . and store in a list, then just print out the list.

s = 'Hello. I am damn cool. Lol'
lines = s.split('.')
for line in lines:
  print(line)

If you do this, the output will be:

Hello
 I am damn cool
 Lol

To remove leading spaces, you could split based on . (with a space), or else use lstrip() when printing.

So, to do this for a file:

# open file for reading
with open('file.txt') as fr:
  # get the text in the file
  text = fr.read()
  # split up the file into lines based on '.'
  lines = text.split('.')

# open the file for writing
with open('file.txt', 'w') as fw:
  # loop over each line
  for line in lines:
    # remove leading whitespace, and write to the file with a newline
    fw.write(line.lstrip() + '\n')
Colin Ricardo
  • 16,488
  • 11
  • 47
  • 80