Benjamin
Benjamin

Reputation: 315

Inline Python "for" to read lines from file and append to list

I have this code:

self.y_file = with open("y_file.txt", "r") as g: y_data.append(line for line in g.readlines())

But it doesn't seem to work and I am more than sure the problem lies within 1) How I open the file (with) and that for loop. Any way I could make this work?

Upvotes: 0

Views: 484

Answers (1)

eran
eran

Reputation: 6921

you can just open and read. If you want auto-close you need to wrap it in function

self.y_file = open('y_file.txt').readlines()

Or:

   def read_file(fname):
      with open(fname) as f:
        return f.readlines()


   self.y_file = read_file('y_file.txt')

Upvotes: 1

Related Questions