Python OS module
OS Module
The Python OS module works with files and directories especially.
To import os module
There are having many methods of os module. Following are some of the methods of OS module.
1.os.access(path,mode)
This method uses the real uid/gid to test for access to a path. If access is allowed, it returns True. Else, it returns False. The first argument is the path; the second is the mode. The mode can take one of four values:
- os.F_OK — Found
- os.R_OK — Readable
- os.W_OK — Writable
- os.X_OK — Executable
Ex
>>> os.chdir(“C:\python”)
>>> os.getcwd() ‘C:\\python’ >>> os.access(‘thefile.txt’,os.F_OK) True >>> os.access(‘thefile.txt’,os.R_OK) True >>> os.access(‘thefile.txt’,os.W_OK) True >>> os.access(‘thefile.txt’,os.X_OK) True |
Note: For working with OS module I have chosen a file which was already created (‘thefile.txt’).
2. os.chdir(path)
This will change the current working directory to the path we specified.
Ex
>>> os.chdir(‘C:\python’) |
‘C:\python’ is not the default path we can set as per our need. It prints nothing. If you want to check if the directory is changed or not, then
>>> os.getcwd()
‘C:\\python’ |
3.os.close(fd)
It closes the associated file with descriptor fd.
Ex
>>> fd=os.open(‘thefile.txt’,os.O_RDWR)
>>> os.close(fd) |
Here it returns no value.
4.os.listdir(path)
This will return a list holding the names of the entries in the directory at the path.
Ex
5. os.pipe( )
It creates a pipe. Then, it returns a pair of descriptors- r & w- for reading and writing.
Ex
>>> os.pipe()
(12, 13) |
6. os.stat(path)
This Python os Module performs a stat system call on the specified path.
These are the members of the stat structure:
- st_mode − protection bits
- st_ino − inode number
- st_dev − device
- st_nlink − number of hard links
- st_uid − user id of owner
- st_gid − group id of owner
- st_size − size of file, in bytes
- st_atime − time of most recent access
- st_mtime − time of most recent content modification
- st_ctime − time of most recent metadata change.
Ex
>>> stat=os.stat(‘purchase1.py’) >>> stat os.stat_result(st_mode=33206, st_ino=562949953580744, st_dev=3457331182, st_nlink=1, st_uid=0, st_gid=0, st_size=334, st_atime=1518192184, st_mtime=1533064593, st_ctime=1518192184) |