我从my csv字段中获取了一些额外的数据,例如“('value',)”。如何从我的价值中删除它。我从昨天开始搜索,但没有任何对我有用。请帮我。提前致谢。
我的模特
from django.db import models
# Create your models here.
class CSVReader(models.Model):
Run = models.CharField(max_length=100, null=True, blank=True)
Model = models.CharField(max_length=100, null=True, blank=True)
Name = models.CharField(max_length=100, null=True, blank=True)
Odometer = models.CharField(max_length=100, null=True, blank=True)
VIN = models.CharField(max_length=100, null=True, blank=True)
BidType = models.CharField(max_length=100, null=True, blank=True)
Ammount = models.CharField(max_length=100, null=True, blank=True)
BuyerName = models.CharField(max_length=100, null=True, blank=True)
class UploadFile(models.Model):
upload = models.FileField(upload_to='csv_files')
我的观点
# -*- coding: utf-8 -*-
import os, re
import csv
import string
from django.shortcuts import render
from .forms import UploadFileForm
from django.shortcuts import HttpResponseRedirect
from .models import CSVReader, UploadFile
def CSV(request):
if request.method == "POST":
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
up = UploadFile.objects.create()
up.upload = request.FILES['upload']
up.save()
path='C:\data_ZXcwWnf.csv'
remove = "'(),"
with open(path, 'rb') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
c= CSVReader.objects.create()
if row[1]!='':
c.Run = row[1].replace("('", '').split("')"),
temp = row[1].replace("('", '').split("')"),
print temp
if row[2] != '':
c.Model = row[2].replace(remove,"_"),
if row[3] != '':
c.Name = row[3].replace(remove,"_"),
if row[4] != '':
c.Odometer = row[4].replace(remove,"_"),
if row[5] != '':
c.VIN = row[5].replace(remove,"_"),
if row[6] != '':
c.BidType = row[6].replace(remove,"_"),
if row[7] != '':
c.Ammount = row[7].replace(remove,"_"),
if row[8] != '':
c.BuyerName = row[8].replace(remove,"_")
print c.Run, c.Model
c.save()
return HttpResponseRedirect('/home/')
else:
print form.errors
print request.FILES
return HttpResponseRedirect('/CSV_app/index/')
else:
form = UploadFileForm(UploadFile)
return render(request, 'CSV_app/index.html', {'form': form})
我的输出是:
(['Run#'],)
(['Run#'],) ('Model',)
([' 23-182'],)
([' 23-182'],) ('2013',)
None None
None None
([' 23-183'],)
([' 23-183'],) ('2013',)
None None
None None
([' 23-185'],)
([' 23-185'],) ('2013',)
None None
([' 23-186'],)
([' 23-186'],) ('2013',)
None None
([' 23-187'],)
([' 23-187'],) ('2013',)
答案 0 :(得分:2)
您应该将视图替换为:
if row[1]!='':
c.Run = row[1]
temp = row[1]
print temp
if row[2] != '':
c.Model = row[2]
if row[3] != '':
c.Name = row[3]
if row[4] != '':
c.Odometer = row[4]
if row[5] != '':
c.VIN = row[5]
if row[6] != '':
c.BidType = row[6]
if row[7] != '':
c.Ammount = row[7]
if row[8] != '':
c.BuyerName = row[8]
答案 1 :(得分:1)
本准则:
c.Run = row[1].replace("('", '').split("')"),
temp = row[1].replace("('", '').split("')"),
替换为:
c.Run = row[1]
temp = row[1]
现在工作正常。