讀取文件並將其分離到不同的列表中。

[英]Read file and separate to different lists


below is my CSV dataset.

下面是我的CSV數據集。

a,d,g

b,e,h

c,f,i

I would like to separate these 3 column as row[0], row[1], and row[2]. And also to make them as 3 different lists.

我想把這3列分別為行[0]、行[1]和行[2]。並把它們列成3個不同的列表。

Here is my code:

這是我的代碼:

import csv

file1 = open('....my_path.csv')


Row_0 = [row[0].upper() for row in csv.reader(file1)]
Row_1 = [row[1].upper() for row in csv.reader(file1)]
Row_2 = [row[2].upper() for row in csv.reader(file1)]

print Row_0
print Row_1
print Row_2

However, I only can see Row_0 result from the console. But the Row_1 and Row_2 are always showing [ ]. Which means I only can see the first row, but not the second and following rows.

但是,我只能看到來自控制台的Row_0結果。但是Row_1和Row_2總是顯示[]。這意味着我只能看到第一行,而不是第二行和下一行。

['A', 'B', 'C']
[]
[]

Does anyone can help me to deal with this "simple" issue?

有人能幫我解決這個“簡單”的問題嗎?

2 个解决方案

#1


3  

open returns an iterator, which becomes exhausted (no longer usable) after you iterate through it once. Moreover, each time you do csv.reader(file1), csv.reader will try to iterate over the iterator referenced by file1. This means that, after the first call, this iterator will become exhausted and all subsequent calls to csv.reader will be using an empty iterator.

open返回一個迭代器,當您遍歷它一次之后,它就會變得很累(不再可用)。此外,每次您執行csv.reader(file1), csv。reader將嘗試遍歷file1引用的迭代器。這意味着,在第一次調用之后,這個迭代器將會被耗盡,並且所有后續的csv調用都將被耗盡。reader將使用一個空迭代器。

To do what you want, you would need something like:

做你想做的事,你需要:

import csv

file1 = open('....my_path.csv')


Row_0, Row_1, Row_2 = ([row[0].upper(), row[1].upper(), [row[2].upper()]
                       for row in csv.reader(file1))

print Row_0
print Row_1
print Row_2

Now, we get all of the data in one read and only iterate over the iterator once.

現在,我們把所有的數據都放在一個讀中,並且只遍歷迭代器一次。

Also, in case you are wondering, the code I used is known as a generator expression. You could also use a list comprehension:

另外,如果您想知道,我所使用的代碼被稱為生成器表達式。你也可以使用列表理解:

Row_0, Row_1, Row_2 = [[row[0].upper(), row[1].upper(), [row[2].upper()]
                       for row in csv.reader(file1)]

but I don't see a point in building a list just to throw it away.

但是我沒有看到建立一個名單只是為了扔掉它。

#2


0  

You've read through the whole file! check out the file position after your first comprehension,

你已經通讀了整個文件!在你的第一次理解之后檢查文件的位置,

You could seek(0) between comprehensions or just iterate once, or reopen the file as @kdopen stated

您可以在理解之間尋找(0),或者只迭代一次,或者像@kdopen聲明的那樣重新打開文件。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2014/12/15/72f326945dbb5f2665d2292acda8235a.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com