【问题标题】:exit a for statement and write stream into a new file in python退出for语句并将流写入python中的新文件
【发布时间】:2017-07-10 01:04:59
【问题描述】:

我是一个 python 初学者,我尝试获取一个网络收音机并将流保存在一个文件中。我想在一段时间后刷新内容(例如只保留 1 小时的流)。所以我不会把所有的流都写在一个文件中,我会尝试将流存储在多个文件中(output_1.bin 一分钟,output_2.bin 下一分钟……)

但我无法正确退出“for”。 exit() 不是为了这个目的?

def download_file(url):
    r = requests.get(url, stream=True)
    i = 1
    while True:
        local_filename = "output_"+str(i)+".bin"
        with open(local_filename, 'wb') as f:
            for chunk in r.iter_content(chunk_size=1024):
                if chunk: # filter out keep-alive new chunks
                    f.write(chunk)
                    i = i+1
                    print("iteration",i,"and modulo result :",i % 10,"\n")
                    if i % 10 == 0:
                        exit()
        f.close()
        print("Am I out of the for ?")
    return local_filename

download_file('http://direct.franceinfo.fr/live/franceinfo-lofi.mp3')

【问题讨论】:

  • exit() 退出进程。你可能想要break
  • 我想你可能正在寻找 break 命令而不是 exit()
  • 顺便说一句,即使退出进程也不应该在脚本中使用exit()(它仅用于交互使用),而应使用sys.exit()
  • ...而您的 while 循环也没有退出条件。

标签: python file for-loop stream


【解决方案1】:

exit() 退出 python 应用程序。你要的是break

【讨论】:

  • 哇呼快回答!太完美了……抱歉,我找不到正确的命令。我需要等待 15 分钟才能接受您的回答
  • 然后f.close() 将在“关闭文件的操作”上崩溃,因为 with 块已经关闭了文件。
  • 没错,您不需要f.close(),因为您在with 块中打开了文件。
猜你喜欢
  • 2019-05-04
  • 2020-09-17
  • 2017-02-02
  • 1970-01-01
  • 2016-05-21
  • 1970-01-01
  • 2017-08-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多