2

I'm using idle in OS X, and I'm trying to parse a file with .data extension:

FP = open('<filename>.data','r')
lines=FP.readlines()
print lines

but this prints an empty array: []

I also tried Sublime but also doesn't work. What is another method to use in Python to read this?

Bond
  • 16,071
  • 6
  • 30
  • 53
makansij
  • 9,303
  • 37
  • 105
  • 183

3 Answers3

1

open it in binary mode and print the repr of its contents instead

print os.stat("filename.data") #ensure that st_size > 0

with open("filename.data","rb") as f:
    print repr(f.read())

if this gives an empty string than you indeed have an empty file ...

im guessing ls -l tells you that the file is 0 bytes big?

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
0

instead of .readlines() you can cast a file pointer to a list which automatically gets all the lines. So you can do this:

FP = open('filename.data', 'r')
print(list(FP))

or this:

FP = open('filename.data', 'r')
for line in FP:
    print(line)
Raghav Malik
  • 751
  • 1
  • 6
  • 20
  • I did see this alternative in the docs, but it gives the same result. – makansij Jul 06 '15 at 23:41
  • do you have any other code in the script other than that? One possible issue is that if you have already read all the lines in a file you can't re-read them because the reading pointer has already reached the end of the file. – Raghav Malik Jul 06 '15 at 23:43
  • It has never worked though - so that's why I didn't think the cursor would be at the end of the file. But anyway, how do I reset the cursor at the beginning? – makansij Jul 06 '15 at 23:49
  • At before reading anything from the file the first time do this: `start = FP.tell()` (this saves the start location of the file) and then whenever you want to go back to the beginning do `FP.seek(start)` which will tell the file pointer to go back to the start location you saved earlier. – Raghav Malik Jul 06 '15 at 23:51
  • I know but if the file has been read through previously in the program then the pointer would be at the end. That's why I asked if there's any other code in the script that might have read through it already. – Raghav Malik Jul 06 '15 at 23:55
0

When opening a file just by filename, Python by default will first look in the current working directory. If you're using IDLE, this may not actually be the same directory in which you're .py file is. Try running your script from the command line in the same directory as your "*.data" file.

Brent Taylor
  • 867
  • 1
  • 9
  • 12
  • If you're not getting an error on opening the file, then the file does exist and it is being opened. I can only conclude that the file is actually empty. Can you dump the contents of your .data file? Or at minimum create a new data file with dummy data? Can you also dump the console output of "ls -la" from the directory containing your .py and .data file? – Brent Taylor Jul 06 '15 at 23:51