python生成文件

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)
复制代码

 

posted @   八戒不爱吃西瓜  阅读(2173)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示