繁体   English   中英

将数据从CSV保存到Python列表

[英]Save Data from CSV to List Python

我想ro读取并保存CSV数据到列表并发送到服务器。 我的算法:1.打开CSV文件。2.检查CSV文件中的数据,如果CSV文件中没有我不想保存的数据,但是如果CSv中有数据,则数据将保存到列表并发送到服务器。 3.读取后删除数据

我在步骤2和3中遇到问题,因为我的系统没有将任何空白数据发送到服务器。 我使用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

你能帮助我吗?

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

您需要首先检查文件是否为空。 即如果是否包含行,请使用csv模块导入csv文件,并将其转换为字典,然后检查其是否为空。.如果为空,则返回None,否则返回数据。 检查以下代码是否相同。

 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