1.生成一般文件(一般几KB到几十M)

import random
#写入文件
def writeFile(n):
    filepath = 'D:\python\locust\\files'
    file = filepath + '\\test.txt'
    SALT_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    with open(file,'w',encoding='utf-8') as f:
        size = n*1024*1024
        for i in range(size):
            f.write(random.choice(SALT_CHARS))
    print(file)

#从文件读取指定大小
def readFile(file):
    with open(file,'r',encoding='utf-8') as f:
        data = f.read(10)
        print(data)

writeFile(5)

aa = 'D:\python\locust\\files\\test.txt'
readFile(aa)

 

2.生成大文件

'''
先使用seek函数为打开的文件偏移一个很大的空间,然后写入数据即可。
seek() 方法用于移动文件读取指针到指定位置。
'''
import random
def writeBigFile(n):
    filepath = 'D:\python\locust\\files'
    file = filepath + '\\test1.txt'
    with open(file,'w',encoding='utf-8') as f:
        f.seek(n*1024*1024*1024-1)    #2048M
        f.write('k')

writeBigFile(2)