user1994660
user1994660

Reputation: 5613

Why did the os.read return empty in second call in python

I try this

fd = os.open("myfd.txt",os.O_RDWR)


In [28]: os.read(fd,24)
Out[28]: 'my test is good\n'

In [29]: os.read(fd,24)
Out[29]: ''

why did it return empty during second call

also when print fd it returns 3 as filedescriptor , what is meant by number 3

Upvotes: 0

Views: 394

Answers (2)

Thomas
Thomas

Reputation: 3381

When you made that first read call, the file pointer moved 24 bytes (or characters) ahead, so you probably hit the end of the file.

And 3 is just a descriptor, it doesn't have any meaning to anything else than the operating system. The reason it's 3 is because descriptors 0, 1, and 2 are already taken by default (0 = stdin, 1 = stdout, 2 = stderr)

Upvotes: 0

mgilson
mgilson

Reputation: 310079

Because at that point, the file pointer is positioned at the end of the file (due to the first read pulling out all the data). It looks like you need an os.lseek to reset the file pointer:

print os.read(fd,24)
os.lseek(fd,0,0)
print os.read(fd,24)

Note that normal file objects are typically much easier to work with if you can help it:

with open('filename') as fin:
    print fin.read(24)
    fin.seek(0)
    print fin.read(24)

Upvotes: 1

Related Questions