Reputation: 75
I have a tex file contains about 1000 line like this:
(1, '0109_S3.p9.m13')
['(n-k)/2']
(2, '0109_S3.p5.m8')
['\\sigma_{i}+\\sigma_{j}']
I want to delete the first 2 and the last 2 characters from the even lines and delete the first and last characters from the odd lines. this is my function:
def remove_chars(filename):
with open(filename, 'r') as f0:
with open('new1.tex', 'a') as f1:
for num, line in enumerate(f0, 1):
if num % 2 == 0:
f1.write(line[2:-2])
else:
f1.write(line[1:-1])
f1.write('\n')
the result should be like this:
1, '0109_S3.p9.m13'
(n-k)/2
2, '0109_S3.p5.m8'
\sigma_{i}+\sigma_{j}
but I get this:
1, '0109_S3.p9.m13')
(n-k)/2'
2, '0109_S3.p5.m8')
\\sigma_{i}+\\sigma_{j}'
so it is deleting the first characters right but not the last. I can not see where is the problem coming from! Could you help with this please?
Upvotes: 0
Views: 34
Reputation: 1121724
Your file lines include a newline character at the end; you are removing that character. You probably just want to remove it only if it is there:
with open('new1.tex', 'a') as f1:
for num, line in enumerate(f0, 1):
line = line.rstrip('\n')
if num % 2 == 0:
f1.write(line[2:-2])
else:
f1.write(line[1:-1])
f1.write('\n')
Upvotes: 2
Reputation: 6358
The lines may contain a line terminator character \n
at the end. You should that that into account, too.
Upvotes: 0