簡體   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