程序无法打印正确的CSV输出

时间:2018-07-19 19:46:03

标签: python django csv

我正在使用Django开发一个Web应用程序,供用户上传2个不同的csv文件,然后该Web应用程序找到这些差异,分别标记差异,然后将其打印为输出。当我运行代码时,它没有给我正确的输出。这是 views.py

from django.shortcuts import render
from django.http import HttpResponse
import difflib
import datetime
import csv
from django.http import HttpResponseRedirect
from django.http import FileResponse
from .forms import FileForm
from .forms import UploadFileForm

def handle_uploaded_file(file1,file2): # handle_uploaded_file is a function that takes 2 files uploaded by the users
    fileone = file1.readlines() # define fileone and read lines from 1st file
    filetwo = file2.readlines() # define filetwo and read lines from 2nd file
    fileone =[line.decode("utf-8").strip() for line in fileone]
    filetwo =[line.decode("utf-8").strip() for line in filetwo]

    csv_old = csv.reader(fileone, delimiter=',')
    count = 0
    header = next(csv_old)
    old_data = {}
    for row in csv_old:
        old_data[count] = row
        count += 1

    csv_new = csv.reader(filetwo, delimiter=',')
    count = 0
    header = next(csv_new)
    new_data = {}
    for row in csv_new:
        new_data[count] = row
        count += 1

    set_new_data = set(new_data)
    set_old_data = set(old_data)

    added = [['Added'] + new_data[v] for v in set_new_data - set_old_data]
    deleted = [['Deleted'] + old_data[v] for v in set_old_data - set_new_data]
    in_both = set_old_data & set_new_data
    changed = [['Changed'] + new_data[v] for v in in_both if old_data[v] != new_data[v]]

    with open('results.csv', 'w', newline='') as f_output:
        csv_output = csv.writer(f_output, delimiter=',')
        csv_output.writerow(['History'] + header)
        csv_output.writerows(sorted(added + deleted + changed, key=lambda x: x[1:]))

def index(request): # index is a function for the upload button
    if request.method == 'POST': # POST method inserts something to the server
        print(request.FILES)
        form = UploadFileForm(request.POST, request.FILES)
        print(form.errors)
        if form.is_valid():
            print("cool")
            handle_uploaded_file(request.FILES.get('file1'),request.FILES.get('file2'))
            return HttpResponseRedirect('results/')
    else:
        form = UploadFileForm()
    return render(request, 'hello.html', {'form': form})

def results(request): # results is a function that sends difference.csv back to the user once the file is ready
    file_path = (r'C:\Users\Public\Documents\PycharmProjects\filecomparison\results.csv') #  adding an absolute path in the server, pinpoints that exact file, very important, r is to produce raw string and handle unicodeescape error
    response = FileResponse(open(file_path, 'rb'))
    response['Content-Type'] = 'text/csv' # the type of the file that will be send is .txt/.csv
    response['Content-Disposition'] = 'attachment; filename=results.csv' # produces an attachment file for users to download called with difference in .csv file
    return response

这里是 sample1.csv

Planet  Account ID  First Name  Last Name   Premise Station City
Earth   1234    Pete    Montgomery  Unknown     Phoenix
Earth   1234    Pete    Montgomery  Unknown     Phoenix
Nebula  1234    Pete    Montgomery  Unknown     Phoenix
Neptune 1234    Pete    Montgomery  Unknown     Phoenix

这是 sample2.csv

Planet  Account ID  First Name  Last Name   Premise Station City
Earth   1234    Pete    Montgomery  Unknown     Montgomery
Earth   1234    Pete    Montgomery  Unknown     Minneapolis
Neptune 1234    Pete    Montgomery  Unknown     Phoenix
Mercury 1234    Pete    Montgomery  Unknown     Eden Gate

* STATION应该具有0条信息(0行),仅用于测试目的

这是我得到的 output.csv

History Planet  Account ID  First Name  Last Name   Premise Station City
Changed Earth   1234    Pete    Montgomery  Unknown     Minneapolis
Changed Earth   1234    Pete    Montgomery  Unknown     Montgomery
Changed Mercury 1234    Pete    Montgomery  Unknown     Eden Gate
Changed Neptune 1234    Pete    Montgomery  Unknown     Phoenix

这是预期的输出

History Planet  Account ID  First Name  Last Name   Premise Type    Station City
Changed Earth   1234    Pete    Montgomery  Unknown     Montgomery
Changed Earth   1234    Pete    Montgomery  Unknown     Minneapolis
Deleted Nebula  1234    Pete    Montgomery  Unknown     Phoenix
Added   Mercury 1234    Pete    Montgomery  Unknown     Eden Gate

。感谢您的任何帮助,谢谢!

1 个答案:

答案 0 :(得分:0)

这项工作吗?

with open('results.csv', 'w', newline='') as f_output:
   csv_output = csv.writer(f_output, delimiter=',') #this line is moved up 
   csv_output.writerow(['History'] + header)
   csv_output.writerows(sorted(added + deleted + changed, key=lambda x: x[0:]))