Reputation: 193
I asked a question about this earlier but noone could answer me - I have this code and want what is defined as e to be written into a new ASCII file in one line. I was suggested to use the tuple function which didn't work since it only takes on argument but I have two (a and b). So now I just tried the join function. The code is below
we=open('new.txt','w')
with open('read.txt') as f:
for line in f:
#read a line
a,b=line.split('\t')
#get two values as string
c=2*int(a)
d=3*int(b)
#calculate the other two values
### edited
e = ''.join(("(",str(a),",",str(b),")"))
However, when I print e the last bracket will be moved to a new line:
print(e)
will yield
(1,2
)
(3,4
)
but I want
(1,2)
(3,4)
Thanks for your help!
Upvotes: 0
Views: 1381
Reputation: 2966
You need to replace the \n
in your lines before extracting your values. This should give the desired output:
with open('read.txt') as f:
for line in f:
# read values
a, b = line.replace("\n", "").split('\t')
# get and parse values
e = ''.join(("(",str(2*int(a)),",",str(3*int(b)),")"))
print(e)
Upvotes: 0
Reputation: 2729
It sounds like b has a \n
(a newline character) at the end. b.strip()
will return b
with all of the whitespace on both sides removed. You could replace
a,b=line.split('\t')
with
a,b=line.strip().split('\t')
or replace e = ''.join(("(",str(a),",",str(b),")"))
with e = ''.join(("(",str(a),",",str(b.strip()),")"))
Upvotes: 2