【问题标题】:Python: Skipping lines from filePython:从文件中跳过行
【发布时间】:2013-10-25 01:37:44
【问题描述】:

我有一个包含 100 行的数据文件,我想创建一个跳过前两行的字典,然后创建一个字典,其中枚举键并将行作为值。

myfile = open(infile, 'r')
d={}
with myfile as f:
    next(f)
    next(f)
    for line in f:

这就是我得到的,我不知道如何使用 iteritems()、enumerate() 或 itervalues(),但我觉得如果有人可以帮助我,我想我会使用它们,也可能不会。

【问题讨论】:

  • 感谢您发布您的代码,但请在您的问题中添加更多描述:您遇到了什么问题,您期望的结果是什么,到目前为止what have you tried

标签: python file dictionary


【解决方案1】:

可以执行以下操作:

from itertools import islice
with open(infile, 'r') as myfile:
  d = dict(enumerate(islice(myfile, 2, None)))

但我希望我明白你为什么要跳过前两行——你确定你不想linecache吗?

【讨论】:

    【解决方案2】:

    这只是我的头等大事,所以肯定会有改进的余地。


    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
    

    我不记得代码中的哪个位置最好关闭文件,但做一些实验并阅读thisthis。另一个好的起点是google 和一般的python docs

    【讨论】:

    • 最好使用with 语句而不是显式关闭文件——with 块将负责关闭文件,即使出现错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-23
    • 1970-01-01
    • 1970-01-01
    • 2016-01-31
    • 1970-01-01
    • 2021-06-28
    • 2013-07-23
    相关资源
    最近更新 更多