Python 结果获胜';不能写入txt文件

Python 结果获胜';不能写入txt文件,python,file,Python,File,即使最后使用了file.flush(),也不会将任何数据写入txt文件 # some essential code to connect to the server while True: try: # do some stuff try: gaze_positions = filtered_surface['gaze_on_srf'] for gaze_pos in gaze_positions:

即使最后使用了
file.flush()
,也不会将任何数据写入txt文件

# some essential code to connect to the server

while True:
    try:
        # do some stuff
        try:
            gaze_positions = filtered_surface['gaze_on_srf']
            for gaze_pos in gaze_positions:
                norm_gp_x, norm_gp_y = gaze_pos['norm_pos']

                if (0 <= norm_gp_x <= 1 and 0 <= norm_gp_y <= 1):
                    with open('/the/path/to/the/file.txt', 'w') as file:
                            file.write('[' + norm_gp_x + ', ' + norm_gp_y + ']')
                            file.flush()
                    print(norm_gp_x, norm_gp_y)
        except:
            pass
    except KeyboardInterrupt:
        break
#一些连接到服务器的基本代码
尽管如此:
尝试:
#做点什么
尝试:
注视位置=过滤的注视表面['凝视\u在\u srf']
对于凝视位置中的凝视位置:
norm_gp_x,norm_gp_y=凝视位置['norm_pos']
如果(0得到它:

首先

因此,您正在添加字符串和整数。这会触发一个异常,因为您使用了一个通用的
except:pass
构造,所以代码会跳过每次迭代(请注意,这个
except
语句也会捕获您试图在更高级别捕获的
KeyboardInterrupt
异常,因此这也不起作用)

切勿使用该构造。如果要保护特定异常(例如:IOError),请使用:

所以你的例外是1)重点突出,2)冗长。始终等待,直到您得到要忽略的异常,才有选择地忽略它们(读取)

因此,您的write it解决方案是:

file.write('[{},{}]'.format(norm_gp_x, norm_gp_y))
或者使用
列表
表示,因为您试图模拟它:

file.write(str([norm_gp_x, norm_gp_y]))
旁白:您的另一个问题是您应该使用附加模式


或者将open语句移动到循环之前,否则您将只获得文件中的最后一行(经典),因为
w
模式在打开文件时会截断文件。退出上下文关闭文件后,您可以删除
flush

您是否100%确定您的
if
语句的计算结果为True,并且执行了
file.write
?A将帮助我们诊断问题。@Aran Fey是的,我编辑了我的问题。如果不在文件中写入任何内容,我将得到一个输出。
除了:pass
是一种非常糟糕的错误处理方式。如果你没有得到print语句,那是因为你得到了一个异常。@Garrettguierrez它确实打印了一个输出。什么是:
#做一些事情
?这是问题所需要的,因为回答者需要能够复制问题。否则,您将获得
NameError:name“filtered_surface”未定义
,并且仅当您摆脱
try/except:pass时才可以。如果你不把它去掉,显然你什么也得不到。哇。漂亮的斑点!是的。异常处理失败。已经在您的评论中看到它,并开始在我的代码中编辑它。谢谢刚刚注意到另一件事:即使我同时放置了
norm\u gp\u x
norm\u gp\u y
我的txt文件显示的值仅为
norm\u gp\u x
的两倍?不过,我的输出是正确的。哈哈哈,我的
格式
参数中有一个输入错误。x变量被重复,该死的复制粘贴。
try IOError as e:
   print("Warning: got exception {}".format(e))
file.write('[{},{}]'.format(norm_gp_x, norm_gp_y))
file.write(str([norm_gp_x, norm_gp_y]))
with open('/the/path/to/the/file.txt', 'a') as file: