1. Home
  2. Computing & Technology
  3. Python

Using File Descriptors in Python's os Module

By Al Lukaszewski, About.com

2 of 5

What Is a File Descriptor, Anyway?

With the file open, you can assign its content to a variable output with input.readlines() and then print it as you like. All of this can happen without knowing the file's descriptor. But what if you want to handle more advanced tasks like getting the status of the file or taking only the first 1024 bytes? For these you need the file descriptor, abbreviated fd. To get it, simply run the fileno() method of the file handle:
input.fileno()
In my shell session, Python returned '3'. If you open another file and follow the same procedure without doing anything else in the terminal, you will get '4'. Knowing the file descriptor, we can resolve the first of the aforementioned problems by calling fstat():
>>> os.fstat(3)
(33188, 5225L, 11L, 1, 1000, 1000, 5834L, 1209359646, 1209359726, 1209359726)
This returns, among other things, the file's group ID, user ID, size, inode, and sundry other bits about its status on the system. If you are on a Unix variant, You can get even more information about the file by running os.fstatvfs(3).

Index: Using File Descriptors in Python's os Module

  1. Opening a File
  2. What Is a File Descriptor, Anyway?
  3. lseek() and ye can read()
  4. More File Handling Calls - Part 1
  5. More File Handling Calls - Part 2

2 of 5

Explore Python

More from About.com

  1. Home
  2. Computing & Technology
  3. Python
  4. Python Library
  5. Python Modules - Python Library - System Programming With the os Module

©2008 About.com, a part of The New York Times Company.

All rights reserved.