2017-01-24 43 views
-1

我想从文本文件创建一个字典。Python - 从文件中创建数组的字典

的文本文件:

***Comment line - not to be read by program*** 
jdoe | doe | John Doe | 0001 | True 
jsmith | smith | John Smith | 0002 | False 

字典将最好的样子:

accounts = { 
'jdoe' : ['doe','John Doe', '0001', True], 
'jsmith' : ['smith', 'John Smith', '0002', False] 
} 

将需要此代码是什么工作?

+1

这将是一个简单得多的[JSON](https://docs.python.org/3/library/json.html) – ti7

+0

欢迎StackOverflow上。请阅读并遵守帮助文档中的发布准则。 [在主题](http://stackoverflow.com/help/on-topic)和[如何提问](http://stackoverflow.com/help/how-to-ask)适用于此处。 StackOverflow不是一个编码或教程服务。 – Prune

+0

@ ti7为什么json会更简单?许多程序读写csv的。我们对这些数据的来源一无所知,修改这些数据源可能非常困难。 json是一个序列化协议,不是邪教。 – tdelaney

回答

1

一个简单的解决办法是:

accounts={} 
with open("replacethiswithrealfilename") as f: 
    for line in f: 
     line=line.strip() 
     if line.startswith("***") or not line: 
      continue # ignore comments, ignore empty lines 
     sl=[s.strip() for s in line.split("|")] 
     sl[-1]=(sl[-1]=="True") 
     accounts[sl[0]]=sl[1:] 
0

我只是回答它,所以你有东西,但是,你应该阅读一些Python编程书籍。

b = {} #your final dictionary 
a = "jdoe | doe | John Doe | 0001 | True" # for loop through the lines in a file, this is just one line 
a = a.split('|') #splits up your string into a list 
b[a[0]] = a[1:] # {'jdoe ': [' doe ', ' John Doe ', ' 0001 ', ' True']} 
1

事情是这样的:

text_file_path = r'your_path' 

accounts = {} 
with open(text_file_path) as f: 
    for line in f.readlines()[1:]: 
     info = line.split(' | ') 
     if info: # possibly ignore blank line at end of file 
      key, values = info[0], info[1:] 
      values[-1] = values[-1] == 'True' 
      accounts[key] = values 

print(accounts) 
0

可以使用csv模块读取文件的元组的行和创建从字典那是可迭代的。复杂的因素是注释行,但可以使用生成器在发布者看到它们之前将其剥离。把它放在一起,你会得到

import csv 

def strip_comments(fp): 
    """iterate uncommented lines of a file""" 
    for line in fp: 
     if not line.startswith('***'): 
      yield line 

with open('test.csv', 'r', newline='') as in_file: 
    reader = csv.reader(strip_comments(in_file), delimiter="|", skipinitialspace=True) 
    accounts = {row[0]:row[1:] for row in reader}