假设我具有以下数据集
10,"XG16008168",9/12/2017 0:00:00,9/13/2017 0:00:00,2/23/2018 0:00:00,"Whatever","07210","25978","Main","Yes",3/9/2018 0:00:00,,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,,0,,0,0,0,0,0,0,0,0,0,1,,0,,0,,0,0,0,0,0,1,0,0,0,0,0,0,,0,
11,"X000000000",11/30/2017 0:00:00,9/25/2017 0:00:00,2/27/2018 0:00:00,"Whatever 004","07210","25978","Main","Yes",3/9/2018 0:00:00,,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,,0,,0,0,0,0,0,0,0,0,0,1,"Missing valve number.",0,,0,,0,0,0,0,0,0,1,0,0,0,0,0,,0,
我使用以下方法读取了此CSV文件:
with open("AccessTable.txt", "r") as RTCData:
with open("RTCOutput.csv", "w") as RTCOutput:
ALLRows = csv.reader(RTCData, delimiter=',')
for row in ALLRows:
rows.append(row)
print(row[1][1])
我正在尝试打印CSV文件的元素。
因此,通过打印row[1][1]
我本来期望"X000000000"
,但是却得到"1"
,它是"11"
中的第二个字符。
能否请您告诉我如何吐出如何提取元素?
答案 0 :(得分:1)
您正在使用row [1] [1],但它应该是row [1]。
尝试在python shell中打印行,您将能够轻松地分析内容。每个项目的示例索引值,行是项目列表。
with open("/home/lavanya/Desktop/AccessTable.txt", "r") as RTCData:
with open("RTCOutput.csv", "w") as RTCOutput:
ALLRows = csv.reader(RTCData, delimiter=',')
for row in ALLRows:
rows.append(row)
print row
print(row[1][1])
答案 1 :(得分:0)
您显示的是row
,而不是rows
,因此您显示的是每行第二个元素中的字符。
答案 2 :(得分:0)
>>> import csv
>>> with open('eggs.csv', 'rb') as csvfile:
... spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
... for row in spamreader:
... print(', '.join(row))
Spam, Spam, Spam, Spam, Spam, Baked Beans
Spam, Lovely Spam, Wonderful Spam
答案 3 :(得分:0)
只需一点点清理,以备将来使用和回答。使用for row in ALLRows:
语句时,已经在所有行中进行迭代。这意味着row
现在包含:
11,"X000000000",11/30/2017 0:00:00,9/25/2017 0:00:00,2/27/2018 0:00:00,"Whatever 004","07210","25978","Main","Yes",3/9/2018 0:00:00,,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,,0,,0,0,0,0,0,0,0,0,0,1,"Missing valve number.",0,,0,,0,0,0,0,0,0,1,0,0,0,0,0,,0,
如果要遍历THAT的各个项目,则可以执行以下操作
# Put both open statements on a single line. A bit cleaner, but does the same thing.
with open("AccessTable.txt", "r") as RTCData, open("RTCOutput.csv", "w") as RTCOutput:
ALLRows = csv.reader(RTCData, delimiter=',')
# Make a huge array from the CSV file
rows = [row for row in ALLRows]
rows.append(row)
# OR
for row in ALLRows:
# Iterate through all of the cells of this row
for cell in row:
print(cell)
# And to access a single item of the row:
part_number = row[1]
祝你好运!