0

Hi I was wondering how I could format a large text file by adding line breaks after certain characters or words. For instance, everytime a comma was in the paragraph could I use python to make this output an extra linebreak.

bman
  • 1
  • Sounds like a better job for sed (https://www.gnu.org/software/sed/manual/sed.html). Something like `sed ‘s/,/,\n/’` – cole Nov 13 '18 at 20:42
  • Possible duplicate of [Split a string by a delimiter in python](https://stackoverflow.com/questions/3475251/split-a-string-by-a-delimiter-in-python) – mrk Nov 13 '18 at 21:13

2 Answers2

1

You can do using str.replace() in python. Check out the below code, replacing every , with ,\n.

string = ""
with open('test.txt','r') as myfile:
  for line in myfile:
    string += line.replace(",",",\n")
myfile.close()
myfile = open('test.txt','w')
myfile.write(string)

File before execution:

Hello World and again HelloWorld,sdjakljsljsfs,asdgrwcfdssaasf,sdfoieunvsfaf,asdasdafjslkj,

After Execution:

Hello World and again HelloWorld,
sdjakljsljsfs,
asdgrwcfdssaasf,
sdfoieunvsfaf,
asdasdafjslkj,
Sanchit Kumar
  • 1,545
  • 1
  • 11
  • 19
0

you can use the ''.replace() method like so:

'roses can be blue, red, white'.replace(',' , ',\n') gives 'roses can be blue,\n red,\n white' efectively inserting '\n' after every ,

vencaslac
  • 2,727
  • 1
  • 18
  • 29