Reputation: 66320
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
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
Reputation: 59594
I would use out.write(line.rstrip('\r\n') + '\n')
, to add a newline to every line without duplication.
Upvotes: 0
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
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
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
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