bonifacill
bonifacill

Reputation: 13

Python writing in two lines instead of one

def end_aluguer(self, nickname):
    a = self.obj_aluguer(nickname)
    x = "{},{},{},{},{},{}\r".format(int(a.time), a.nickname, a.viatura, a.preco, a.decorrido(), a.update())
    y = open("historico.txt", 'a')
    y.write(x)
    y.close()

Hello, so i have this function and everything is working fine except when it writes in historico.txt it splits into two lines:

1607741371,tiagovski,tartaruga,0.80

,21,0.0

How can i make it to write in only one line? Thanks in advance for your time

Upvotes: 1

Views: 154

Answers (2)

costaparas
costaparas

Reputation: 5237

It appears your data hasn't been sanitized fully yet - it hasn't been cleaned.

One of your fields, in this case, a.preco has newline(s) already in it -- hence, it is being written out to the file, resulting in a broken output.

Generally this:

a.preco.strip()

will suffice. But do note that this will also remove any leading and trailing whitespace (which you often want to do anyway).

Otherwise, you can specifically remove just the newline character(s) from the end using rstrip, like this:

a.preco.rstrip('\n')

and this will retain the leading and trailing whitespace.

Also, you may want to do the same with your other fields, depending on where your data is coming from and whether you can rely on it being in a suitable format.

Upvotes: 1

Hirusha Fernando
Hirusha Fernando

Reputation: 1305

Try this code

def end_aluguer(self, nickname):
    a = self.obj_aluguer(nickname)
    x = "{},{},{},{},{},{}\r".format(int(a.time), a.nickname, a.viatura, a.preco, a.decorrido(), a.update())
    x = ' '.join(x.split('\n'))    # remove newline and join into one string
    y = open("historico.txt", 'a')
    y.write(x)
    y.close()

Upvotes: 0

Related Questions