1

I have text file containing numbers with different number of newlines. How can I remove the new lines except the ones.

Example of numbers I have in text file

1

2




3


4

2

If I do open('thefile.txt').read().replace('\n', '') I will get everything in one line. How can I get output like this.

1
2  
3
4
2

1 Answers1

1

I think it would be better to just remove all lines that only contain whitespaces and join the remaining ones afterwards:

For example:

with open('thefile.txt') as myfile:
    result = '\n'.join([line.strip() for line in myfile if line.strip()])

print(result)

Or if you don't want to strip twice:

result = '\n'.join([line for line in map(str.strip, myfile) if line])

or using filter instead of a comprehension:

result = '\n'.join(filter(bool, map(str.strip, myfile)))
MSeifert
  • 145,886
  • 38
  • 333
  • 352