【问题标题】:Stop Python Script from Writing to File after it reaches a certain size in linux在Linux中达到一定大小后停止Python脚本写入文件
【发布时间】:2014-12-11 19:09:33
【问题描述】:

对 Python 和 linux 有点陌生。我创建了一个脚本来挖掘 Twitter 的流 API。当流中的内容与我的参数匹配时,脚本会写入 .csv 文件。

我想知道一旦文件达到 1 gig 是否有任何方法可以停止我的脚本。我知道 cron 可用于对脚本和所有内容进行计时,但我更关心文件大小而不是所花费的时间。

感谢您的意见和考虑。

【问题讨论】:

    标签: python linux twitter


    【解决方案1】:

    在您的情况下,您可能不需要 os.statos.stat 在某些情况下可能会给您错误的大小(即缓冲区未刷新)。为什么不直接使用f.tell() 来读取大小这样的东西

    with open('out.txt', 'w', encoding='utf-8') as f:
        csvfile = csv.writer(f)
        maxsize = 1024                # max file size in bytes
        for row in data():
            csvfile.writerow(row)
            if f.tell() > maxsize:    # f.tell() gives byte offset, no need to worry about multiwide chars
                break
    

    【讨论】:

    • 效果很好。我很感激。
    【解决方案2】:

    使用 python 的os.stat() 获取文件信息,然后检查现有文件 (fileInfo.st_size) 的总字节数加上您要写入的数据的大小。

    import os
    fileInfo = os.stat('twitter_stream.csv')
    fileSize = fileInfo.st_size
    print fileSize
    
    # Now get data from twitter
    # determine number of bytes in data
    # write data if  file size + data bytes < 1GB
    

    【讨论】:

    • 效果也很好。感谢您帮助我解决这个问题。
    猜你喜欢
    • 1970-01-01
    • 2017-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    • 2011-08-05
    • 2012-12-09
    相关资源
    最近更新 更多