1

I am trying to get the contents of a file in a list. For reference: these are the contents of the file:

1. item1
2. item2
3. item3

I am able to open the files, and when I do file.read(), all I get from the interpreter is an empty string:

>>> file = open("C:\\Users\\vivrd\\Desktop\\testing.txt")
>>> file.read()
''

If I do file.readlines(), it displays a list, but even though the python docs say that file.readlines() returns a list, whenever I try to assign a variable to it (to access the list), all I get is an empty list:

>>> file.readlines() 
['1. item1\n', '2. item2\n', '3. item3'] #returns the list   
>>> item = file.readlines()
>>> item #but the list is empty!
[]

I have also tried to loop through the file, but it doesn't print out anything:

>>> for line in file:
print(line)


>>> 

Also, for some reason, file.readlines() is only working once. I tried it a second time, and the interpreter didn't even display anything:

>>> file.readlines()
[]

My target is to get a list that looks like this: ["1. item1", "2. item2", "3. item3"] or even with the escape sequences (though not preferable): ["1. item1 \n", "2. item2 \n", "3. item3"]

How can I get to this point? Thanks!

2 Answers2

3

It will work only once, because after that, python is done reading the file (here's a question that discusses this in detail). Read it once and store it in a variable:

>>> f = open("C:\\Users\\vivrd\\Desktop\\testing.txt")
>>> items = f.readlines() # items should now be a list of lines in the file
>>> f.close() # make sure to close the file

If you want to re-read, move the 'cursor' back to the beginning of the file (before closing) using seek:

>>> items = f.readlines()
>>> f.seek(0)
>>> more_items = f.readlines()
>>> f.close()
slider
  • 12,810
  • 1
  • 26
  • 42
1

Try with these lines of codes .

with open(filename , "r") as file:
     content=file.readlines()
for lines in content:
    print(lines)
sameer_nubia
  • 721
  • 8
  • 8