2017-04-17 77 views
1

文件是一样的东西:Python 3中,打开CSV文件导入到一个字典

6, 'bird', 'flies', False 

,它需要订购,如:

{'bird': (6,'flies', False)} 

这是我有这么远,但在格式化权。

{"'bird'": '1'} 

我当前的代码:

def read_info_file(filename): 

    d = {} 
    count = 0 

    file = open(filename, "r") 
    lines = file.readlines() 

    for line in lines: 
     split = tuple(line.split(",")) 

     if count > 0: 
      d[split[1]] = split[0] 
     count += 1 

    return d 

我也不会在这个问题上导入任何模块。

+2

此外,** **显示我们你所说的 “不正确格式化” 的意思。 –

+1

此外,您可能会发现使用内置的[csv模块]更容易(https://docs.python.org/3/library/csv.html) – roganjosh

回答

1

下面根据您的格式要求来格式化csv。

代码:

导入CSV

从pprint进口pprint

DEF过滤(STR):

str = str.strip().strip("'") 
return str 

DEF read_info_file(文件路径):

try: 

    res = {} 

    csvfile = open(filepath,'r') 
    csv_reader = csv.reader(csvfile) 

    for row in csv_reader: 
     res[filter(row[1])] = (int(row[0]),filter(row[2]),bool(row[3])) 

except Exception as e: 
    print("Exception occurred: " + str(e)) 
finally: 
    csvfile.close() 
return res 

解析度= read_info_file( 'FILE.CSV') pprint(RES)

输出:

{ '动物':(7, '苍蝇',真), '鸟' :(6,'flies',True), '昆虫':(8,'苍蝇',True)}

+1

您解开了我的编辑并打破了您的答案格式。 – roganjosh

+0

我可悲的是不能为这个问题导入任何东西 – AnonyMoose

2

用Python解析csv文件通常比它值得的工作更多。这里有一个简单的方法来解析各行,使用发电机,同时仍使用csv模块:

代码:

import csv 

def parse_my_csv(csv_file): 
    for line in csv_file.readlines(): 
     # replacing comma/space with comma 
     yield line.replace(", ", ",") 

with open('myfile.csv', 'rU') as csvfile: 
    csv_read = csv.reader(parse_my_csv(csvfile), quotechar="'") 
    for row in csv_read: 
     d = {row[1]: (int(row[0]), row[2], bool(row[3]))} 
     print(d) 

结果:

{'bird': (6, 'flies', True)} 
0

要做到这一点没有任何进口模块,你可以使用类似的理解:

代码:

def read_info_file(filename): 
    with open(filename, 'rU') as f: 
     return {row[1]: (int(row[0]), row[2], bool(row[3])) 
       for row in [ 
        [c.strip().strip("'") for c in line.split(',')] 
        for line in f.readlines() 
       ]} 

测试:

print(read_info_file('myfile.csv')) 

结果:

{'bird': (6, 'flies', True)}