我不想手动执行解析CSV的部分,我需要以这种方式访问单元格:
Cells (row, column) = X
或
X = Cells (row, column)
有谁知道怎么做?
答案 0 :(得分:3)
尝试:
import csv
sheet = list(csv.reader(open(source_csv_location)))
print sheet[0][0]
答案 1 :(得分:3)
根据您需要的复杂程度,pandas可能会很好。
import pandas as pd
location = r'C:\path\to\your\file.csv'
df = pd.read_csv(location, names=['Names','Births'])
df['Births'].plot()
答案 2 :(得分:2)
假设您有一个CSV文件,并希望将其视为一个数组:
您可以使用numpy
模块中的genfromtxt
,这将生成一个numpy数组,其行和列与文件中的行数相同(X
代码如下)。假设数据是全部数字,您可以使用savetxt
在csv文件中存储值:
import numpy as np
X = np.genfromtxt("yourcsvfile.dat",delimiter=",")
X[0,0] = 42 # do something with the array
np.savetxt('yourcsvfile.dat',X,delimiter=",")
修改强>
如果文件中有字符串,您可以这样做:
# read in
X = np.genfromtxt("yourcsvfile.dat",delimiter=",",dtype=None)
# write out
with open('yourcsvfile.dat','w') as f:
for el in X[()]:
f.write(str(el)+' ')
答案中的其他一些技巧:
numpy save an array of different types to a text file
How do I import data with different types from file into a Python Numpy array?