Houman
Houman

Reputation: 66320

Easier way to add "\n" to all output lines in Python?

The following script works for me, but I wonder if it could be done in an easier way. I am using Python 2.7.3.

f = open('file.txt')
out = open('script.sql', "w")
for line in f:
        out.write('%s%s' % (line[:-1], '\n'))
f.close()
out.close()

Thanks,

Upvotes: 0

Views: 178

Answers (7)

octopusgrabbus
octopusgrabbus

Reputation: 10685

Before you write the contents of line out to the file, using line.rstrip like this:

out.write(line.rstrip('\r\n') + '\n')

will remove any existing carriage-returns or line-feeds '\r' or '\n`, and will add a newline to every line.

Upvotes: 0

warvariuc
warvariuc

Reputation: 59594

I would use out.write(line.rstrip('\r\n') + '\n'), to add a newline to every line without duplication.

Upvotes: 0

user688635
user688635

Reputation:

If you use print, the \n is added automagically:

print >>out, line[:-1]

It is suggested these days to use with like so:

with open('file.txt') as f, open('script.sql', "w") as out:
    for line in f:
       print >>out, line[:-1]

# autoclosed f and out...

Upvotes: 2

mgilson
mgilson

Reputation: 309831

In this case, it seems a little redundant to strip the newline and add it again:

f = open('file.txt')
out = open('script.sql', "w")
for line in f:
     out.write(line)
f.close()
out.close()

Or better, use shutil to copy the file directly.

Upvotes: 2

stranac
stranac

Reputation: 28226

You can either just add a \n by using line[:-1] + '\n', or you can use a simpler formatting, like '%s\n' % (line[:-1],).

Upvotes: 3

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250881

don't use the old %s string formatting use format()

   out.write('{0}{1}'.format(line[:-1], '\n'))

or out.write('{0}\n'.format(line[:-1]))

Upvotes: 3

Cat Plus Plus
Cat Plus Plus

Reputation: 129764

Well, there's line[:-1] + '\n'.

Upvotes: 6

Related Questions