[英]Python: putting rows data from a csv file into a list
我在與Python腳本相同的目錄中有一個CSV文件,我想獲取該數據並將其轉換為列表,以便以后使用。 我更喜歡使用Python的CSV模塊。 在閱讀了該模塊的文檔和有關該模塊的問題之后,我仍然沒有找到任何幫助。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv
inputfile = 'inputfile.csv'
inputm = []
reader = csv.reader(inputfile)
for row in reader:
inputm.append(row)
point1,point2,point3,point4
0,1,4,1
0,1,1,1
0,1,4,1
0,1,0,0
0,1,2,1
0,0,0,0
0,0,0,0
0,1,3,1
0,1,4,1
它僅返回我提供的文件名的字符串。
[['i'], ['n'], ['p'], ['u'], ['t'], ['f'], ['i'], ['l'], ['e']]
我希望將CSV文件的每一行作為子列表返回,而不是將文件名的每個字母作為子列表返回。
您需要以讀取模式打開文件,讀取內容! 那是,
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv
inputfile = 'inputfile.csv'
inputm = []
with open(inputfile, "rb") as f:
reader = csv.reader(f, delimiter="\t")
for row in reader:
inputm.append(row)
輸出:
[['point1,point2,point3,point4'], ['0,1,4,1'], ['0,1,1,1'], ['0,1,4,1'], ['0,1,0,0'], ['0,1,2,1'], ['0,0,0,0'], ['0,0,0,0'], ['0,1,3,1'], ['0,1,4,1']]
您實際上需要open()
文件:
inputfile = open('inputfile.csv')
您可能需要查看with
語句:
with open('inputfile.csv') as inputfile:
reader = csv.reader(inputfile)
inputm = list(reader)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.