【问题标题】:Save Data from CSV to List Python将数据从 CSV 保存到列表 Python
【发布时间】:2016-01-05 19:38:46
【问题描述】:

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

我在第 2 步和第 3 步遇到问题,因为我的系统没有向服务器发送空白列表。 我使用 python 2.7 并且有我的代码: `def readFile(self): 尝试: 打印“打开”+ self.filename f = 打开(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

你能帮帮我吗?

【问题讨论】:

    标签: python csv


    【解决方案1】:

    是不是因为函数返回 None 没有附加到 Data,然后你将 None 发送到服务器进行保存?

    【讨论】:

    • 如果没有我不发送到服务器。我使用sendMessage 将数据发送到服务器。
    【解决方案2】:

    你需要先检查文件是否为空。即是否包含行,使用 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
    

    【讨论】:

      【解决方案3】:
      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"
      

      【讨论】:

      • 谢谢。在我读入 csv 文件后,你能帮我看看删除行的代码吗?
      • 是的,在我读取帽子数据后,我想删除所以文件 CSV 为空。 @s.gaynetdinov
      猜你喜欢
      • 1970-01-01
      • 2016-03-14
      • 2016-08-20
      • 2016-05-17
      • 2016-12-21
      • 2017-08-14
      • 2018-06-05
      • 1970-01-01
      • 2022-07-06
      相关资源
      最近更新 更多