1

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

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

11 Comments

I am still getting the same error Exception Type: AttributeError Exception Value: 'str' object has no attribute 'read'
I am getting this error at this line: decoded_file = filename.read() It's not accepting to read filename variable.What can cause this ?
i edit this line: decoded_file = fs.open(filename) . try and tell me if works
filename is the name of the file that it is save. And you need open the file with the name of filename in fs. You change this line in your code: decoded_file = filename.read().decode('utf-8') with this line decoded_file = fs.open(filename).read().decode('utf-8')
Yes now it works.:) Thank you very much for your interest.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.