'Striping space while preserving new line separator python
I want to strip spaces to single space but preserve one empty line separator in a file. I have tried the following code and it seems to work.
How can I do this with out writing to the file twice?
I want to collect all my substitutions may be in a text file and write them all at once.
i = open('inputfile.txt','r')
infile = i.readlines()
o = open('outputfile.txt','w')
for line in infile:
if line == '\n':
o.write('\n\n')
else:
o.write(re.sub(r'\s+',' ',line))
o.close()
i.close()
Solution 1:[1]
i = open('inputfile.txt','r')
infile = i.readlines()
o = open('outputfile.txt','w')
newoutputfile = ""
for line in infile:
if line == '\n':
newoutputfile+= '\n\n'
else:
newoutputfile +=' '.join(line.split())
o.write(newoutputfile)
o.close()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ashwini Chaudhary |
