结果不会被写入txt文件

时间:2018-03-19 19:44:30

标签: 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:
                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

我做错了什么?显然我想念一些东西,但我无法弄明白,它是什么。另一个奇怪的事情是:print(norm_gp_x, norm_gp_y)甚至没有输出。如果我将with open ...放在评论中,我将获得输出。

1 个答案:

答案 0 :(得分:6)

得到了它:

第一

if (0 <= norm_gp_x <= 1 and 0 <= norm_gp_y <= 1):

然后:

file.write('[' + norm_gp_x + ', ' + norm_gp_y + ']')

所以你要添加字符串和整数。这会触发异常,并且由于您使用了通用except: pass构造,因此代码会跳过每次迭代(请注意,此except语句还会捕获您尝试捕获的KeyboardInterrupt异常在更高的层次上,这样做也不起作用)

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

try IOError as e:
   print("Warning: got exception {}".format(e))

所以你的例外是1)专注和2)冗长。总是等到你得到忽略的异常才会忽略它们,有选择地(阅读Catch multiple exceptions in one line (except block)

所以你的写作修复:

file.write('[{},{}]'.format(norm_gp_x, norm_gp_y))

或使用list表示,因为您尝试模仿它:

file.write(str([norm_gp_x, norm_gp_y]))

除此之外:您的另一个问题是您应该使用追加模式

with open('/the/path/to/the/file.txt', 'a') as file:

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