简体   繁体   English

PYTHON:上传文本文件,然后每 n 行拆分成较小的文本文件

[英]PYTHON: Upload text file then split into smaller text files in every n lines

I'm having a problem splitting my file.我在拆分文件时遇到问题。 This is my code for uploading a file.这是我上传文件的代码。

def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        file = request.FILES['file']
        return HttpResponse(str(file) + "is uploaded")  
    else:
        form = UploadFileForm()
    return render(request, 'upload.html',{'form':form})

I don't have any idea how to split the file that was uploaded.我不知道如何拆分上传的文件。 Like in every 20 lines, it'll split into smaller text files like this: File(1).txt, File(2).txt.... Thanks in advance!就像每 20 行一样,它会拆分成更小的文本文件,如下所示:File(1).txt, File(2).txt.... 提前致谢!

def break_file(filepath,lines):
    file=None
    with open(filepath) as largefile:
        for n,text in enumerate(largefile): #goes through each line
            if n%lines ==0 : 
                if file: #check if previous file is already open.
                    file.close() 
                file_num = 1+ n/lines # 1 if you want file name to start from1
                file_name = 'File({}).txt'.format(file_num)
                file= open(file,"w") 
            file.write(text)
        if file:
            file.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM