Python, cannot open a text file

Question:

I have a text file named android.txt (with a couple of thousand of lines) which I try to open with python, my code is:

f = open('/home/user/android.txt', 'r')

But when I’m doing:

f.read()

the result is:

''

I chmod 777 /home/user/android.txt but the result remains the same

Asked By: woshitom

||

Answers:

You are not displaying the contents of the file, just reading it.

For instance you could do something like this:

with open('/home/user/android.txt') as infp:
    data = infp.read()

print data # display data read 

Using with will also close the file for your automatically

Answered By: Vaulstein

The result would be empty string not empty list and it’s because your file size is larger than your memory(based on your python version and your machine)! So python doesn’t assigned the file content to a variable!

For getting rid of this problem you need to process your file line by line.

with open('/home/user/android.txt') as f :
    for line in f:
         #do stuff with line
Answered By: Mazdak

try making a variable that contains f:read() and printing it

f = open('/home/user/android.txt', 'r')
rf = f:read()
print(rf)

else try making print(repr(f:read()))

Answered By: freziyt223
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.