İlkem Çetinkaya
İlkem Çetinkaya

Reputation: 214

django read dynamic csv file error

I wrote Django python csv reader but it's not working properly. I can see the file is uploaded to the system, but I can't read it and I'm getting the error below:

Exception Type: AttributeError 
Exception Value:     'str' object has no attribute 'read'
data = csv.reader(open('tmp/tmp.csv'), delimiter=";")

When I am using as per above statically ,it's working but I need the dynamic one that I am receiving via file upload. I need your help because I am out of options to solve this. I know that decoded_file, io_string and data variables are not working correctly but can't fix them.

def upload_csv(request):
    if request.method == 'POST' and request.FILES['csv_file']:
        myfile = request.FILES['csv_file']
        fs = FileSystemStorage()
        filename = fs.save(myfile.name, myfile)

        decoded_file = filename.read().decode('utf-8')
        io_string = io.StringIO(decoded_file)
        data = csv.reader(io_string, delimiter=';', quotechar='|')
        for row in data:
            if row[0] != 'FP_Item':
               post = FP()
               post.FP_Item = row[0]
               post.save()

CSV File: Not much because still import trials, only 2 lines.There was ; at the end but I deleted and retried still the same

5.Item try
Try

Upvotes: 1

Views: 507

Answers (1)

blacker
blacker

Reputation: 798

You try to read a string in csv.reader. you change your code in upload_csv:

def upload_csv(request):
    if request.method == 'POST' and request.FILES['csv_file']:
        myfile = request.FILES['csv_file']
        fs = FileSystemStorage()
        filename = fs.save(myfile.name, myfile)
        print "filename",filename
        data = csv.reader(fs.open(filename, mode='r'), delimiter=str(u';').encode('utf-8'), quotechar=str(u'"').encode('utf-8'))
        for row in data:
            print "row: ",row

Upvotes: 2

Related Questions