Introduction to the more practical functions of the python os.path module
This article is reproduced from: http://www.cnblogs.com/BeginMan/p/3327291.html
An overview of the os module
The Python os module contains common operating system functions. This module is especially important if you want your program to be platform independent. (in one sentence)
2. Commonly used methods
1、os.name
The output string indicates the platform in use. 'nt' for window, 'posix' for Linux/Unix users.
2、os.getcwd()
The function gets the current working directory, that is, the directory path where the current Python script works.
3、os.listdir()
Returns all file and directory names in the specified directory.
os.listdir(os.getcwd())
[‘Django’, ‘DLLs’, ‘Doc’, ‘include’, ‘Lib’, ‘libs’, ‘LICENSE.txt’, ‘MySQL-python-wininst.log’, ‘NEWS.txt’, ‘PIL-wininst.log’, ‘python.exe’, ‘pythonw.exe’, ‘README.txt’, ‘RemoveMySQL-python.exe’, ‘RemovePIL.exe’, ‘Removesetuptools.exe’, ‘Scripts’, ‘setuptools-wininst.log’, ‘tcl’, ‘Tools’, ‘w9xpopen.exe’]
4、os.remove()
Delete a file.
5、os.system()
Run shell commands.
os.system('dir')
0
os.system('cmd') #Start dos
6. os.sep can replace operating system specific path separators.
7. The os.linesep string gives the line terminator used by the current platform
os.linesep
'\r\n' #Windows uses '\r\n', Linux uses '\n' and Mac uses '\r'.
os.sep
'\' #Windows
8 os.path.split ()
The function returns the directory name and file name of a path
os.path.split(‘C:\Python25\abc.txt’)
(‘C:\Python25’, ‘abc.txt’)
9. The os.path.isfile() and os.path.isdir() functions check whether the given path is a file or a directory, respectively.
os.path.isdir(os.getcwd())
True
os.path.isfile(‘a.txt’)
False
10. The os.path.exists() function is used to check whether the given path really exists
os.path.exists(‘C:\Python25\abc.txt’)
False
os.path.exists(‘C:\Python25’)
True
11. os.path.abspath(name): get the absolute path
12. os.path.normpath(path): standard path string form
13. os.path.getsize(name): Get the file size, if name is a directory, return 0L
14. os.path.splitext(): separate file name and extension
os.path.splitext(‘a.txt’)
(‘a’, ‘.txt’)
15. os.path.join(path,name): connect a directory with a file name or directory
os.path.join(‘c:\Python’,’a.txt’)
‘c:\Python\a.txt’
os.path.join(‘c:\Python’,’f1’)
‘c:\Python\f1’
16. os.path.basename(path): returns the file name
os.path.basename(‘a.txt’)
‘a.txt’
os.path.basename(‘c:\Python\a.txt’)
‘a.txt’
17. os.path.dirname(path): returns the file path
os.path.dirname(‘c:\Python\a.txt’)
‘c:\Python’