简体   繁体   English

Python 写成两行而不是一行

[英]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:你好,所以我有这个 function 并且一切正常,除了它在historyo.txt中写入时它分为两行:

1607741371,tiagovski,tartaruga,0.80 1607741371,tiagovski,tartaruga,0.80

,21,0.0 ,21,0.0

How can i make it to write in only one line?我怎样才能让它只写一行? Thanks in advance for your time在此先感谢您的时间

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.您的一个字段,在这种情况下, a.preco中已经有换行符 - 因此,它被写入文件,导致 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:否则,您可以使用rstrip从末尾删除换行符,如下所示:

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.此外,您可能希望对其他字段执行相同的操作,具体取决于您的数据来自何处以及您是否可以依赖它采用合适的格式。

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM