abc1212 abc1212 - 4 months ago 18
Python Question

no "\n" but new line being made?

There is no

in my code but when I print out all my variables, it creates a newline meaning my last variable is printed on another line.

my code :

with open("read_it.txt", "r") as text_file:
for items in text_file:
line = items.split(",")
if GTIN in items:
product = line[1]
indprice = line[2]
finprice = float(indprice)* float(Quantity)

current output (wrong) :

086947367 banana 2 £ 0.50
£ 1.0

I want :

86947367 banana 2 £ 0.50 £ 1.0

any help appreciated.


When you call readline on a file object (which you're doing implicitly in your for loop), it leaves the trailing '\n' and/or '\r' characters. In this case, your indprice variable still contains that trailing '\n'.


line = items.strip('\r\n').split(',')

Or, if it's a small text file that you can pull entirely into memory:

for items in'\n'):