Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 写入命令不';不要把所有的东西都打印在同一行上_Python_File - Fatal编程技术网

Python 写入命令不';不要把所有的东西都打印在同一行上

Python 写入命令不';不要把所有的东西都打印在同一行上,python,file,Python,File,我在循环中使用以下命令打开一个.txt文件,并在该文件上写入一些结果 with open ('results.txt', 'a') as file: file.write('%s %d %s %s \n' %(timestamp, v, str(dcur), str(gcur))) 但是,结果不会打印在.txt文件的同一行上,str(gcur)会出现在下一行上 为什么会发生这种情况以及如何解决它?很可能是因为当调用str到dcur时,它会以某种方式添加一个“\n” 您可以剥离它: w

我在循环中使用以下命令打开一个.txt文件,并在该文件上写入一些结果

with open ('results.txt', 'a') as file: 
    file.write('%s %d %s %s \n' %(timestamp, v, str(dcur), str(gcur)))
但是,结果不会打印在.txt文件的同一行上,str(gcur)会出现在下一行上


为什么会发生这种情况以及如何解决它?

很可能是因为当调用
str
dcur
时,它会以某种方式添加一个
“\n”

您可以剥离它:

with open ('results.txt', 'a') as file: 
    file.write('%s %d %s %s \n'.format(timestamp, v, str(dcur).rstript("\n"), str(gcur).rstript("\n")))

很可能是因为当调用
str
dcur
时,它不知何故添加了一个
“\n”

您可以剥离它:

with open ('results.txt', 'a') as file: 
    file.write('%s %d %s %s \n'.format(timestamp, v, str(dcur).rstript("\n"), str(gcur).rstript("\n")))

您正在打印格式字符串
'%s%d%s%s\n'
,其中
%s
%d
时间戳、v、str(dcur)、str(gcur)
变量替换。请注意格式字符串末尾的
\n
-这是换行符。如果希望所有内容都打印在同一行上,则应将其删除,如下所示:

with open ('results.txt', 'a') as file: 
    file.write('%s %d %s %s' %(timestamp, v, str(dcur), str(gcur)))

您正在打印格式字符串
'%s%d%s%s\n'
,其中
%s
%d
时间戳、v、str(dcur)、str(gcur)
变量替换。请注意格式字符串末尾的
\n
-这是换行符。如果希望所有内容都打印在同一行上,则应将其删除,如下所示:

with open ('results.txt', 'a') as file: 
    file.write('%s %d %s %s' %(timestamp, v, str(dcur), str(gcur)))

尝试使用
(timestamp,v,str(dcur).rstrip(“\n”)、str(gcur).rstrip(“\n”)
@AthinaPap这是因为文件中有\n。writei如果字符串
gcur和dcur中没有
\n
,则不应该发生这种情况。你能给出一个完整的输入和输出的例子吗?感谢
(timestamp,v,str(dcur).rstrip(“\n”),str(gcur.rstrip(“\n”))
@athinapp这是因为您的文件中有\n。writei如果字符串
gcur和dcur中没有
\n
,那么它就不会发生。你能给出一个完整的输入和输出的例子吗?谢谢