如何根据嵌套 for 循环中的文件大小创建多个文件?



我正在编写一个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.%dn"%(i,j,k,l))                            
IP() 
IP()

输出:

new_file1.txt
new_file2.txt

您可以简单地测试您的文件。您可能需要使用.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()方法来获取你当前正在编写的流中的位置。不过,这不是文件大小。

最新更新