0
votes

I want ro read and save data from CSV to list and sent to server. My Algorithm: 1. Open CSV file 2. Check data in CSV file, if in CSV file no data I don't want to save to list but if in CSv have data, the Data will save to list and sent to server. 3. Delete data after read

I've got problem in step 2 and 3 for no data my sistem sent blank list to server. I use python 2.7 and there is my code: `def readFile(self): try: print "open " + self.filename f = open(self.filename) csv_f= csv.reader (f)

    except IOError:
        print 'cannot open file'

    else:
        ## Read the first line 

        print "file opened " + self.filename

        ## If the file is not empty keep reading line one at a time
        ## till the file is empty

        for row in csv_f:
            Data.append(row)
            del (row)
        f.close()
        return Data

Can you help me?

3

3 Answers

0
votes

Is it because the function is returning None as nothing appended to Data, then you sent the None to server for saving?

0
votes

You need to first check if the file is empty or not. i.e if contains rows or not, import the csv file using csv module and convert it to dictionary and check if it is empty or not..if empty return None else return data. check the below code for the same.

 with open(file, "rb") as csv_f:         

    csvdict = csv.DictReader(csv_f)
    rows = False
    for line in csvdict:
        rows = True

    if not rows:
        return None
    else:
        for row in csv_f:
            Data.append(row)
            del (row)
        f.close()
        return Data
0
votes
class WorkCSV(object):
    def __init__(self, filename):
        self.filename = filename

    def readFile(self):
        try:
            with open(self.filename) as fd:
                print "open " + self.filename
                row_items = [row for row in fd.xreadlines()]
                print "opened " + self.filename
                if row_items:
                    print row_items
                    return row_items
                else:
                    print "file empty"
                    return None
        except IOError as err:
            print "cannot open file"