我有一个csv格式的数据文件,其中包含口袋妖怪名称和统计信息。我想把它作为一个矩阵读入python。列标题是数据表的第一行,列以逗号分隔,行由“\ n”分隔
pokedex_file = 'pokedex_basic.csv'
with open(pokedex_file, 'r') as f:
raw_pd = f.read()
是我的ecode但是在使用line.strip()时我的内存崩溃了?有什么建议吗?
答案 0 :(得分:0)
根据它的存储方式,您可以使用dictReader读取它。
import csv
with open('/path-name.csv', 'r') as input:
reader = csv.DictReader(input)
for dataDict in reader:
# do stuff with dataDict
stats = dataDict['pokemon_name']
答案 1 :(得分:0)
Python有一个名为csv的包,它可以很容易地解析csv文件。 如果您的CSV文件包含标题,例如
Name,Type
Charizard,Fire/Dragon
Pikachu,Electric
然后您可以使用csv中的DictReader工具来解析您的文件。
import csv
with open('pokemon.csv', 'r') as pokedex:
reader = csv.DictReader(pokedex)
for line in reader: # line is a dict to represent this line of data
print(line)
current_name = line['Name']
current_type = line['Type']
print("The pokemon {:s} has type {:s}".format(current_name, current_type))
输出:
{'Name': 'Charizard', 'Type': 'Fire/Dragon'}
The pokemon Charizard has type Fire/Dragon
{'Name': 'Pikachu', 'Type': 'Electric'}
The pokemon Pikachu has type Electric