我有一个数据文件,它有100行,我想要创建一个字典,它跳过前两行,然后创建一个字典,并以行作为值枚举键。Python:从文件中跳过
myfile = open(infile, 'r')
d={}
with myfile as f:
next(f)
next(f)
for line in f:
这是我得到了什么,我没怎么使用iteritems(),枚举(),或itervalues(),但我觉得我想我会用他们或许不是,如果有人可以帮助我。
我有一个数据文件,它有100行,我想要创建一个字典,它跳过前两行,然后创建一个字典,并以行作为值枚举键。Python:从文件中跳过
myfile = open(infile, 'r')
d={}
with myfile as f:
next(f)
next(f)
for line in f:
这是我得到了什么,我没怎么使用iteritems(),枚举(),或itervalues(),但我觉得我想我会用他们或许不是,如果有人可以帮助我。
这只是我的头顶,所以肯定会有改进的空间。
myfile = open(infile, 'r') # open the file
d = {} # initiate the dict
for line in myfile: # iterate over lines in the file
counter = 0 # initiate the counter
if counter <= 1: # if we have counted under 2 iterations
counter += 1 # increase the counter by 1 and do nothing else
else: # if we have counted over 2 iterations
d[counter - 2] = line # make a new key with the name of lines counted (taking in to consideration the 2 lines precounted)
counter += 1 # increase the counter by 1 before continuing
我不能我的头顶记得在代码这将是最好关闭该文件,但做一些试验和阅读this和this。另一次是开始的好地方通常是google和python docs。
使用'with'语句而不是显式关闭文件可能会更好 - 即使出现错误,'with'块也会关闭文件。 – kojiro
您可以做这样的事情:
from itertools import islice
with open(infile, 'r') as myfile:
d = dict(enumerate(islice(myfile, 2, None)))
但我想我明白了为什么要跳过前两行 - 你肯定不想linecache
?
感谢您发布您的代码,但请在您的问题中多加一点说明:您有什么问题,您期望的结果是什么,以及[您尝试过什么](http://whathaveyoutried.com)远? –