[英]python - read file into dictionary - delimited with curly brackets, no comma delimiter
[英]Python - read comma delimited file into array
我想讀取一個包含數據的文件:
IAGE0,IAGE5,IAGE15,IAGE25,IAGE35,IAGE45,IAGE55
5,5,5.4,4.2,3.8,3.8,3.8
4.3,4.3,4.9,3.4,3,3.7,3.7
3.6,3.6,4.2,2.9,2.7,3.5,3.5
3,3,3.6,2.7,2.7,3.3,3.3
2.7,2.7,3.2,2.6,2.8,3.1,3.1
2.4,2.4,3,2.6,2.9,3,3
因此,我希望數組“ iage0 [1]”讀取為“ 5,並且“ iage15 [1] = 5.4”。可以跳過標題。然后每一行的iage0 [2] = 4.3等...所以一個數組是只是一列。
我以為“ f.readlines(3)”將讀取第3行,但似乎仍讀取第一行。 我需要以某種方式將行拆分為單獨的值。
這是我的代碼,我不知道如何拆分“內容”或閱讀下一行。 很抱歉這個簡單的問題,但是我昨天才開始編碼。
def ReadTxtFile():
with open("c:\\jeff\\vba\\lapseC2.csv", "r") as f:
content = f.readlines(3)
# you may also want to remove whitespace characters like `\n`
content = [x.strip() for x in content]
print("Done")
print(content)
我認為這與您要查找的內容相似。 (Python 3.6)
import csv
d = {}
headers = []
with open('data.csv') as file_obj:
reader = csv.reader(file_obj)
for header in next(reader):
headers.append(header)
d[header] = []
for line in reader:
for idx,element in enumerate(line):
d[headers[idx]].append(element)
print(d)
{'IAGE0': ['5', '4.3', '3.6', '3', '2.7', '2.4'], 'IAGE5': ['5', '4.3', '3.6', '3', '2.7', '2.4'], 'IAGE15': ['5.4', '4.9', '4.2', '3.6', '3.2', '3'], 'IAGE25': ['4.2', '3.4', '2.9', '2.7', '2.6', '2.6'], 'IAGE35': ['3.8', '3', '2.7', '2.7', '2.8', '2.9'], 'IAGE45': ['3.8', '3.7', '3.5', '3.3', '3.1', '3'], 'IAGE55': ['3.8', '3.7', '3.5', '3.3', '3.1', '3']}
print(d['IAGE0'][0])
5
print(d['IAGE15'][0])
5.4
您也可以使用DictReader
d = {}
headers = []
with open('data.csv') as file_obj:
reader = csv.DictReader(file_obj)
for line in reader:
for key,value in line.items():
if key not in d:
d[key] = [value]
else:
d[key].append(value)
print(d)
{'IAGE0': ['5', '4.3', '3.6', '3', '2.7', '2.4'], 'IAGE5': ['5', '4.3', '3.6', '3', '2.7', '2.4'], 'IAGE15': ['5.4', '4.9', '4.2', '3.6', '3.2', '3'], 'IAGE25': ['4.2', '3.4', '2.9', '2.7', '2.6', '2.6'], 'IAGE35': ['3.8', '3', '2.7', '2.7', '2.8', '2.9'], 'IAGE45': ['3.8', '3.7', '3.5', '3.3', '3.1', '3'], 'IAGE55': ['3.8', '3.7', '3.5', '3.3', '3.1', '3']}
print(d['IAGE0'][0])
5
print(d['IAGE15'][0])
5.4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.