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

2024-03-29 10:24:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Django开发一个web应用程序,让用户上传两个不同的csv文件,然后web应用程序找到这些差异,分别标记这些差异,然后将其打印为输出。当我运行代码时,它不会给我正确的输出。这里是视图.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

*工作站应该有0个信息(0行),其位置仅用于测试目的

这里是输出.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

是的。感谢您的帮助,谢谢!你知道吗


Tags: csvtheinfromimportnewfordata
1条回答
网友
1楼 · 发布于 2024-03-29 10:24:55

这是否有效:

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:]))

相关问题 更多 >