简体   繁体   中英

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!

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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