繁体   English   中英

如何将列表中的元组转储到Python中的文本文件中

[英]how to dump tuples in a list to a text file in Python

我有一个包含许多元组的列表,并存储在streaming_cfg

并尝试转储到文本文件DEBUG_STREAMING_CFG_FILE

但它是一个空文件,什么都不包含。 为什么?

    debug_file = open(DEBUG_STREAMING_CFG_FILE,'w')
    for lst in streaming_cfg:
        print(lst)
        debug_file.write(' '.join(str(s) for s in lst) + '\n')
    debug_file.close

streaming_cfg

[('0', '0', 'h264', '1/4', '1280x1024', '10', 'vbr', '27', '8m'),
 ('0', '0', 'h264', '1/4', '1280x1024', '10', 'cbr', '6m', 'framerate'),
 ('0', '0', 'h264', '1/4', '1280x1024', '10', 'cbr', '6m', 'imagequality'),
 ('0', '0', 'h264', '1/4', '1280x1024', '10', 'cbr', '8m', 'framerate'),
 ('0', '0', 'h264', '1/4', '1280x1024', '10', 'cbr', '8m', 'imagequality'),
 ('0', '0', 'h264', '1/4', '2560x1920', '8', 'vbr', '27', '8m'),
 ('0', '0', 'h264', '1/4', '2560x1920', '8', 'cbr', '6m', 'framerate'),
 ('0', '0', 'h264', '1/4', '2560x1920', '8', 'cbr', '6m', 'imagequality'),
 ('0', '0', 'h264', '1/4', '2560x1920', '8', 'cbr', '8m', 'framerate'),
 ('0', '0', 'h264', '1/4', '2560x1920', '8', 'cbr', '8m', 'imagequality'),
 ('0', '0', 'mjpeg', '1/2', '1280x1024', '10', 'vbr', '25', '4m'),
 ('0', '0', 'mjpeg', '1/2', '1280x1024', '10', 'cbr', '6m', 'imagequality'),
 ('0', '0', 'mpeg4', '1/2', '1280x1024', '10', 'vbr', '28', '6m'),
 ('0', '0', 'mpeg4', '1/2', '1280x1024', '10', 'cbr', '3m', 'imagequality')]

你实际上并没有调用close ,你只有一个表达式来计算可调用对象。

替换最后一行

debug_file.close()

顺便说一句,通过使用上下文管理器,可以在现代python中防止这样的错误:

with open(DEBUG_STREAMING_CFG_FILE,'w') as debug_file:
    for lst in streaming_cfg:
        print(lst)
        debug_file.write(' '.join(str(s) for s in lst) + '\n')

现代Python:

with open(DEBUG_STREAMING_CFG_FILE, "w") as f:
    for lst in streaming_cfg:
        print(' '.join(str(s) for s in lst), file=f)

无需关闭打开的文件。

你没有调用close() ,但是如果你使用一个更简单的with子句,你不必要么:

with open(DEBUG_STREAMING_CFG_FILE, 'w') as f:
    for lst in streaming_cfg:
        print(lst)
        f.write(' '.join(str(s) for s in lst) + '\n')

暂无
暂无

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

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