Search code examples
pythonreadlines

Reading lines from file only after hastag symbol Python::


I am trying to read lines from file in python, I searched and found partition/strip however, I got the following error "AttributeError: 'list' object has no attribute 'partition' " file is as the following:

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

I got a way to read last line without #it's ok, is there any better and faster way to read only what I want from the beginning not all the line then remove the part that I do not want:

 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()

Solution

  • Maybe something like this:

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

    The code above removes all comments. Instead if you need to remove the comment from line 2 then:

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