سؤال

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()
هل كانت مفيدة؟

المحلول

See my answer in this question here: Python save file to csv

I think the re.sub() replacement is tripping you up with the '\s' value. Just replace ' ' instead.

نصائح أخرى

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()
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top