加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python:outfile到另一个文本文件,如果超过某个文件大小

发布时间:2020-12-20 12:28:24 所属栏目:Python 来源:网络整理
导读:我在ubuntu中使用scapy和 python.我想问一下是否有人会知道如何编写示例代码: 假设我有两个文本文件在脚本运行时写入然后我想检查文件是否超过示例500bytes,如果它然后它将存储文件中的任何内容并创建一个新的文本文件来编写. (output1.txt,output2.txt等..
我在ubuntu中使用scapy和 python.我想问一下是否有人会知道如何编写示例代码:

假设我有两个文本文件在脚本运行时写入然后我想检查文件是否超过示例500bytes,如果它然后它将存储文件中的任何内容并创建一个新的文本文件来编写. (output1.txt,output2.txt等..)

如果任何专业知识有帮助,将不胜感激.谢谢

我的部分代码是:

file = open("output.txt","w")

def example(p):
    if p.haslayer(Dot11Beacon):
        if p.addr2 not in uniqueAP:
            file.writelines(p.addr2 + "n")

因此,当脚本在终端中运行时,它会将其写入名为output.txt的文件中,但我想改进脚本以检查文本文件的文件大小,如果超过它将停止写入当前并创建一个新的output2.txt例如并继续.

解决方法

一个简单的例子,如果你不想使用 RotatingFileHandler.

您应该使用os.stat(‘filename’).st_size来检查文件大小.

import os
import sys

class RotatingFile(object):
    def __init__(self,directory='',filename='foo',max_files=sys.maxint,max_file_size=50000):
        self.ii = 1
        self.directory,self.filename      = directory,filename
        self.max_file_size,self.max_files = max_file_size,max_files
        self.finished,self.fh             = False,None
        self.open()

    def rotate(self):
        """Rotate the file,if necessary"""
        if (os.stat(self.filename_template).st_size>self.max_file_size):
            self.close()
            self.ii += 1
            if (self.ii<=self.max_files):
                self.open()
            else:
                self.close()
                self.finished = True

    def open(self):
        self.fh = open(self.filename_template,'w')

    def write(self,text=""):
        self.fh.write(text)
        self.fh.flush()
        self.rotate()

    def close(self):
        self.fh.close()

    @property
    def filename_template(self):
        return self.directory + self.filename + "_%0.2d" % self.ii

if __name__=='__main__':
    myfile = RotatingFile(max_files=9)
    while not myfile.finished:
        myfile.write('this is a test')

运行之后……

[mpenning@Bucksnort ~]$ls -la | grep foo_
-rw-r--r--  1 mpenning mpenning    50008 Jun  5 06:51 foo_01
-rw-r--r--  1 mpenning mpenning    50008 Jun  5 06:51 foo_02
-rw-r--r--  1 mpenning mpenning    50008 Jun  5 06:51 foo_03
-rw-r--r--  1 mpenning mpenning    50008 Jun  5 06:51 foo_04
-rw-r--r--  1 mpenning mpenning    50008 Jun  5 06:51 foo_05
-rw-r--r--  1 mpenning mpenning    50008 Jun  5 06:51 foo_06
-rw-r--r--  1 mpenning mpenning    50008 Jun  5 06:51 foo_07
-rw-r--r--  1 mpenning mpenning    50008 Jun  5 06:51 foo_08
-rw-r--r--  1 mpenning mpenning    50008 Jun  5 06:51 foo_09
[mpenning@Bucksnort ~]$

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读