Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
List Python3:拆分列表并另存为文件-如何?_List_Python 3.x_Split - Fatal编程技术网

List Python3:拆分列表并另存为文件-如何?

List Python3:拆分列表并另存为文件-如何?,list,python-3.x,split,List,Python 3.x,Split,我是Python新手,谢谢你的帮助 我想告诉Python获取一个大的.csv列表,并将其拆分为许多只有两列的小列表 以这个.csv文件为例 始终使用第一列“年” 然后始终取下一列(循环?),从第2列“Object1”开始,然后是第3列“Object2”,依此类推 将每个列表另存为.csv(现在仅包含两列),并在第二列后命名(f.e.“Object1”) 到目前为止,我能做到这一点: import csv object = 0 f = open("/home/Data/data.csv") c

我是Python新手,谢谢你的帮助

我想告诉Python获取一个大的.csv列表,并将其拆分为许多只有两列的小列表

  • 以这个.csv文件为例
  • 始终使用第一列“年”
  • 然后始终取下一列(循环?),从第2列“Object1”开始,然后是第3列“Object2”,依此类推
  • 将每个列表另存为.csv(现在仅包含两列),并在第二列后命名(f.e.“Object1”)
  • 到目前为止,我能做到这一点:

    import csv
    object = 0
    
    f = open("/home/Data/data.csv")
    
    csv_f = csv.reader(f, delimiter=';', quotechar='|')
    
    writer = csv.writer(csv_f)
    
    for row in csv_f:
        writer("[0],[object]")
    
        object += 1
    
    f.close()
    

    您的代码试图打开同一文件进行读写,这可能会产生意外的结果

    把你的问题看作一系列步骤;解决这个问题的一种方法是:

  • 打开大文件
  • 读取文件的第一行,其中包含列标题
  • 浏览列标题(大csv文件的第一行),跳过第一行,然后:
  • 对于每个列标题,创建一个新的csv文件,其中文件名是列的名称
  • 取第一列的值加上当前正在读取的列的值,并将其写入文件
  • 重复此操作,直到读取所有列标题
  • 关闭文件
  • 关闭大文件
  • 下面是与上面相同的方法,利用Python的csv读取功能:

    import csv
    
    with open('big-file.csv') as f:
       reader = csv.reader(f, delimiter=';', quotechar='|')
       titles = next(reader)
       for index, column_name in enumerate(titles[1:]):
          with open('{}.csv'.format(column_name), 'w') as i:
             writer = csv.writer(i, delimiter=';', quotechar='|')
             for row in reader:
                writer.writerow((row[0],row[index+1]))
          f.seek(0) # start from the top of the big file again
          next(reader) # skip the header column