【问题标题】:Reading lines from file only after hastag symbol Python::仅在标签符号 Python:: 之后从文件中读取行
【发布时间】:2021-12-14 20:02:40
【问题描述】:

我正在尝试从 python 中的文件中读取行,但我搜索并找到了分区/条带,但出现以下错误“AttributeError:'list' object has no attribute 'partition' " 文件如下:

`    1 
     2
    [[1],[2],[3],np.repeat(3,4)]   #It's ok 
     # I would like to read last line but without #it's ok)

我有办法在没有#it 的情况下阅读最后一行,没关系, 有没有更好更快的方法从头开始只读取我想要的内容而不是所有行然后删除我不想要的部分:

 import numpy as np
 import os
 import os.path
  f    = open('trial_one.dat')
  data = f.readlines()
  dir=data[2]
  f.close()

 LE=dir
 LE=LE.partition("#")[0]
 LE = LE.rstrip()

【问题讨论】:

    标签: python readlines


    【解决方案1】:

    可能是这样的:

     with open('trial_one.dat', 'r') as f:
         data = f.readlines()
         data = [(d+' ')[:d.find('#')].rstrip() for d in data]
         LE = data[2]
    

    上面的代码删除了所有的 cmets。相反,如果您需要从第 2 行删除注释,则:

     with open('trial_one.dat', 'r') as f:
         data = f.readlines()
         LE = data[2]
         LE = (LE+' ')[:LE.find('#')].rstrip()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-04
      • 1970-01-01
      • 1970-01-01
      • 2015-12-15
      • 2014-10-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多