Reputation: 10679
I am having trouble with a really simple problem. I'm trying to remove line breaks in a file and send the output to a new file. This is my code:
infile = open('seq.txt', mode='r', encoding='utf-8')
lines = infile.readlines()
for line in lines:
par = line.strip('\n')
outfile = open('seqpar.txt', mode='w', encoding='utf-8')
for line in lines:
outfile.write(par)
When I run the above code, the contents of the outfile (seqpar.txt) is completely blank. I've tried to search for I/O tutorials online, but I can't seem to locate any solutions to a similar problem. I'm really having trouble with understanding file I/O for some reason.Thanks in advance for the help.
Upvotes: 0
Views: 203
Reputation: 50975
Other answers explain what's wrong with your code. Here's a more pythonic way of doing what you're trying to do:
with open('seq.txt', mode='r', encoding='utf-8') as infile:
with open('seqpar.txt', mode='w', encoding='utf-8') as outfile:
for line in infile:
outfile.write(line.strip("\n"))
# Or alternatively -- more efficient, but perhaps less pythonic:
# outfile.write(infile.read().replace("\n", ""))
Upvotes: 3
Reputation: 50497
The problem with your code is that your first for
loop iterates over each line in the file, putting it in the variable par
, each time overriding the same variable with the next line.
Once the loop as finished, par
will contain the last line of the file, and the next for loop will write the last line of the file to the new file repeated n
times, n
being the number of lines in the first file.
Below is one way that would work:
infile = open('seq.txt', mode='r', encoding='utf-8')
lines = infile.readlines()
outfile = open('seqpar.txt', mode='w', encoding='utf-8')
for line in lines:
outfile.write(line.stripe('\n')
Upvotes: 2
Reputation: 1551
par = line.strip('\n')
This isn't being stored anywhere, so every line
read overwrites the previous par
. Your final line in the input file is presumably blank, and that final line is all that gets written to the output file, so nothing gets written to the output - several times, once for each line in lines
. You need to append each line.strip('\n')
to par
, rather than overwriting it.
Upvotes: 3