简体   繁体   English

将数据从CSV保存到Python列表

[英]Save Data from CSV to List Python

I want ro read and save data from CSV to list and sent to server. 我想ro读取并保存CSV数据到列表并发送到服务器。 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. 我的算法:1.打开CSV文件。2.检查CSV文件中的数据,如果CSV文件中没有我不想保存的数据,但是如果CSv中有数据,则数据将保存到列表并发送到服务器。 3. Delete data after read 3.读取后删除数据

I've got problem in step 2 and 3 for no data my sistem sent blank list to server. 我在步骤2和3中遇到问题,因为我的系统没有将任何空白数据发送到服务器。 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) 我使用python 2.7,有我的代码:`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? 你能帮助我吗?

是否因为该函数返回None而不附加任何数据,然后将None发送到服务器进行保存?

You need to first check if the file is empty or not. 您需要首先检查文件是否为空。 ie 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. 即如果是否包含行,请使用csv模块导入csv文件,并将其转换为字典,然后检查其是否为空。.如果为空,则返回None,否则返回数据。 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
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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM