abc1212 abc1212 - 2 months ago 8
Python Question

no "\n" but new line being made?

There is no

\n
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)
print(GTIN,product,Quantity,"£",indprice,"£",finprice)


current output (wrong) :

086947367 banana 2 £ 0.50
£ 1.0


I want :

86947367 banana 2 £ 0.50 £ 1.0


any help appreciated.

Answer

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'.

Try:

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

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

for items in text_file.read().split('\n'):