简体   繁体   English

为什么os.read在python的第二次调用中返回空

[英]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 同样在打印fd它返回3作为filedescriptor,这是数字3的含义

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: 看来您需要os.lseek来重置文件指针:

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)

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. 当您进行第一个读取调用时,文件指针向前移动了24个字节(或字符),因此您很可能碰到了文件的末尾。

And 3 is just a descriptor, it doesn't have any meaning to anything else than the operating system. 而且3只是一个描述符,它对操作系统没有任何其他意义。 The reason it's 3 is because descriptors 0, 1, and 2 are already taken by default (0 = stdin, 1 = stdout, 2 = stderr) 之所以为3,是因为默认情况下已经使用了描述符0、1和2(0 = stdin,1 = stdout,2 = stderr)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM