社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
私信  •  关注

darksky

darksky 最近创建的主题
darksky 最近回复了
7 年前
回复了 darksky 创建的主题 » python3通过分隔符将大文件拆分为小文件(不是大小、行)

当你在一个 with context with 当你离开这个街区时,会自动为你关门。所以你不需要 file.close() 任何地方。

readlines 它输出一个生成器,该生成器一次从打开的文件中读取一行。这比 read() 后面跟着 split() . 想想看。你在内存中加载一个大文件,然后要求CPU通过 \n 性格。效率不高。

opfile.write(op) . 这是哪里 op 定义?你不想把内容写进 holding 你定义的?

with open('test.data', 'r') as myfile:
    counter = 1
    content = ""
    start = True

    for line in myfile.readlines():
        if line == "-\n" and not start:
            with open(str(counter) + '.md', 'w') as opfile:
                opfile.write(content)

            content = ""
            counter += 1
        else:
            if not start:
                content += line

        start = False

    # write the last file if test-file.yml doesn't end with a dash
    if content != "":
        with open(str(counter) + '.md', 'w') as opfile:
            opfile.write(content)