如何在嵌套的for循环中基于文件大小创建多个文件?

时间:2018-08-25 13:19:37

标签: python python-3.x python-2.7

我正在编写一个Python脚本,用于根据文件大小创建多个文件。

例如:

当大小变为10MB时创建另一个文件。

关于到目前为止我已经尝试过的示例脚本,它正在创建多个文件,但不是基于大小:

global fname
x=1
def IP():
    limit = 1
    i= 255
    for j in range(1,3):
        fname = "new_file"+str(x)+".txt"
        global x
        x += 1
        with open(fname, "a") as new:
            for k in range(1,200):
                for l in range(1,200):
                    new.write("IP is: %d.%d.%d.%d\n"%(i,j,k,l))                            
IP() 
IP()

输出:

new_file1.txt
new_file2.txt

1 个答案:

答案 0 :(得分:0)

您可以简单地测试文件。您可能需要使用.flush()来强制物理检查文件内容,然后再检查其大小,否则操作系统将决定何时刷新文件-缓冲区中的数据可能为4k或8k。

import os
import random 

def rnd():
    r = random.randint
    return [r(1,255),r(1,255),r(1,255),r(1,255)]

x = 1
while True:
    with open("myfile_{}.txt".format(x),"a") as f:
        x += 1
        # reads flushed sizes only
        while os.fstat(f.fileno()).st_size < 300: # size criterium
            f.write("{}.{}.{}.{}\n".format(*rnd()))
            f.flush() # persist to disk so size checking works - this degrades performance
        if x > 10:
            break

for f in os.listdir("./"):
    print(f, os.stat(f).st_size) 

输出:

myfile_10.txt 304
myfile_9.txt 315
myfile_8.txt 313
myfile_4.txt 302
myfile_6.txt 305
myfile_2.txt 306
myfile_5.txt 300
main.py 447
myfile_7.txt 308
myfile_3.txt 303
myfile_1.txt 304

如果您只需要猜测,还可以使用文件句柄.tell()方法来获取当前正在写入的流中的位置。不过,这不是文件大小。