Fundamentals 22 min read

Python os Module Functions Overview and Usage

This article provides a comprehensive guide to Python's os module, detailing common file and directory operations such as creating folders, listing files, deleting files, and retrieving file attributes, with syntax, descriptions, and code examples for each function.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Python os Module Functions Overview and Usage

The os module, a semantic operating‑system interface in Python, provides functions for everyday file and directory operations such as creating folders, obtaining file lists, deleting files, retrieving file sizes, and getting modification times.

Typical operations include creating a new folder, getting a file list, deleting a specific file, obtaining file size, and renaming files. The module contains many OS‑related functions; this article selects the most commonly used ones for clear explanation.

Functions are accessed via os.name and the os.path submodule (e.g., os.path.isfile ). Below are the selected functions with description, syntax, and example code.

1. os.name()

Description: Shows the current platform; 'nt' indicates Windows, 'posix' indicates Linux.

Syntax: os.name

<code>os.name
'nt'</code>

2. os.getcwd()

Description: Returns the current working directory of the process.

Syntax: os.getcwd()

<code>os.getcwd()
'C:\\Users\\wuzhengxiang'</code>

3. os.chdir()

Description: Changes the current working directory to the specified path.

Syntax: os.chdir(path)

<code># view current directory
os.getcwd()
'C:\\Users\\wuzhengxiang'

# change working directory
os.chdir('C:/Users/wuzhengxiang/Desktop/股票数据分析')

# verify change
os.getcwd()
'C:\\Users\\wuzhengxiang\\Desktop\\股票数据分析'</code>

4. os.makedirs()

Description: Recursively creates directories (like mkdir() but also creates intermediate directories).

Syntax: os.makedirs(path, mode=0o777)

<code>os.makedirs('C:/Users/wuzhengxiang/Desktop/股票数据分析/1122', mode=0o777)</code>

5. os.mkdir()

Description: Creates a single directory with the given permission mode (default 0777 ).

Syntax: os.mkdir(path[, mode])

<code>os.mkdir('C:/Users/wuzhengxiang/Desktop/股票数据分析/2233', mode=0777)</code>

6. os.listdir()

Description: Lists all files and sub‑directories in a directory.

Syntax: os.listdir(path)

<code>os.listdir('C:/Users/wuzhengxiang/Desktop/股票数据分析')
['ETF研究.py', 'foo.txt', 'pi.txt', 'render.html']

os.listdir('.')
['ETF研究.py', 'foo.txt', 'pi.txt', 'render.html']</code>

7. os.remove()

Description: Deletes the specified file; raises OSError if the path is a directory.

Syntax: os.remove(path)

<code>os.remove('C:/Users/zhengxiang.wzx/Desktop/timg.jpg')</code>

8. os.rename()

Description: Renames a file or directory.

Syntax: os.rename(src, dst)

Parameters:

src – original name

dst – new name

<code>data_path = 'C:/Users/zhengxiang.wzx/Desktop/微博情绪识别'
os.chdir(data_path)
os.rename('图片下载.py', '图片下载1.py')</code>

9. os.renames()

Description: Recursively renames a file or directory, similar to rename() but can also rename intermediate directories.

Syntax: os.renames(old, new)

<code>os.chdir('C:/Users/wuzhengxiang/Desktop/Python知识点总结')
os.renames('test/Python 63个内置函数详解.py', 'test2/内置函数详解.py')
os.listdir()
['kaggle', 'test2', '股票分析', '课程资源']</code>

10. os.linesep

Description: Platform‑specific line separator (e.g., '\n' on POSIX, '\r\n' on Windows). Use '\n' for text files to ensure cross‑platform compatibility.

Syntax: os.linesep

<code>os.linesep
'\r\n'</code>

11. os.pathsep

Description: Separator used in environment variables like PATH ( ':' on POSIX, ';' on Windows).

Syntax: os.pathsep

<code>os.pathsep
';'</code>

12. os.close()

Description: Closes the file descriptor fd .

Syntax: os.close(fd)

<code>fd = os.open('foo.txt', os.O_RDWR|os.O_CREAT)
os.write(fd, bytes('This is test', encoding='utf8'))
os.close(fd)</code>

13. os.stat()

Description: Retrieves file or directory metadata.

Syntax: os.stat(path)

<code>os.stat('C:/Users/wuzhengxiang/Desktop/股票数据分析\\pi.txt')
os.stat_result(st_mode=33206, st_ino=22236523160361562, st_dev=2419217970, st_nlink=1, st_uid=0, st_gid=0, st_size=53, st_atime=1589638199, st_mtime=1589638199, st_ctime=1581868007)</code>

14. os.sep

Description: Platform‑specific path separator ( '/' on POSIX, '\\' on Windows).

Syntax: os.sep

<code>os.sep
'\\'</code>

15. os.path.abspath()

Description: Returns the absolute path of a file.

Syntax: os.path.abspath(path)

<code># Excel file
os.path.abspath('all_data.xlsx')
'C:\\Users\\zhengxiang.wzx\\all_data.xlsx'

# Image file
os.path.abspath('IMG_7358.JPG')
'C:\\Users\\zhengxiang.wzx\\IMG_7358.JPG'</code>

16. os.path.basename()

Description: Returns the final component of a pathname (the file name).

Syntax: os.path.basename(path)

<code>os.path.basename('C:\\Users\\zhengxiang.wzx\\all_data.xlsx')
'all_data.xlsx'</code>

17. os.path.commonprefix()

Description: Returns the longest common prefix of a list of paths.

Syntax: os.path.commonprefix(list)

<code>os.path.commonprefix(['http://c.biancheng.net/python/aaa', 'http://c.biancheng.net/shell/'])
'http://c.biancheng.net/'

os.path.commonprefix(['http://bianc/python/aaa', 'http://c.biancheng.net/shell/'])
'http://'</code>

18. os.path.dirname()

Description: Returns the directory component of a pathname.

Syntax: os.path.dirname(path)

<code>os.path.dirname('C://my_file.txt')
'C://'

os.path.dirname('C://python//my_file.txt')
'C://python'</code>

19. os.path.exists()

Description: Returns True if the path exists, otherwise False .

Syntax: os.path.exists(path)

<code>os.path.exists('C:/Users/wuzhengxiang/Desktop/股票数据分析/pi.txt')
True

os.path.exists('C:/Users/wuzhengxiang/Desktop/股票数据分析/')
True

os.path.exists('C:/Users/wuzhengxiang/Desktop/股票数据分析/pi_01.txt')
False</code>

20. os.path.lexists()

Description: Returns True if the path exists or is a broken symbolic link; otherwise False .

Syntax: os.path.lexists(path)

<code>os.path.lexists('C:/Users/wuzhengxiang/Desktop/股票数据分析/pi.txt')
True

os.path.lexists('C:/Users/wuzhengxiang/Desktop/股票数据分析/pi_01.txt')
False</code>

21. os.path.expanduser()

Description: Expands ~ or ~user to the user’s home directory.

Syntax: os.path.expanduser(path)

<code>os.path.expanduser('~/wuzhengxiang/Desktop/股票数据分析/')
'C:\\Users\\wuzhengxiang/wuzhengxiang/Desktop/股票数据分析/'</code>

22. os.path.expandvars()

Description: Replaces environment variables like $NAME or ${NAME} with their values.

Syntax: os.path.expandvars(path)

<code>os.environ['KITTIPATH'] = 'D:/thunder'
path = '$KITTIPATH/train/2011_09_26_drive_0001_sync/proj_depth/velodyne_raw/image_02/0000000013.png'
os.path.expandvars(path)
'D:/thunder/train/2011_09_26_drive_0001_sync/proj_depth/velodyne_raw/image_02/0000000013.png'</code>

23. os.path.getatime()

Description: Returns the last access time of a file (seconds since epoch).

Syntax: os.path.getatime(path)

<code>os.path.getatime('C:/Users/wuzhengxiang/Desktop/股票数据分析/pi.txt')
1589638199.1343248</code>

24. os.path.getmtime()

Description: Returns the last modification time of a file (seconds since epoch).

Syntax: os.path.getmtime(path)

<code>os.path.getmtime('C:/Users/wuzhengxiang/Desktop/股票数据分析/pi.txt')
1583069050.8148942</code>

25. os.path.getctime()

Description: Returns the creation time of a file (seconds since epoch).

Syntax: os.path.getctime(path)

<code>os.path.getctime('C:/Users/wuzhengxiang/Desktop/股票数据分析/pi.txt')
1581868007.6123319</code>

26. os.path.getsize()

Description: Returns the size of a file in bytes; raises an error if the file does not exist.

Syntax: os.path.getsize(path)

<code>os.path.getsize('C:/Users/wuzhengxiang/Desktop/股票数据分析/test.gif')
1128677</code>

27. os.path.isabs()

Description: Determines whether a path is absolute.

Syntax: os.path.isabs(path)

<code>os.path.isabs('D:/thunder')
True

os.path.isabs('D:\\thunder')
False

os.path.isabs('D:\\thunder')
True</code>

28. os.path.isfile()

Description: Checks if the given path points to a regular file.

Syntax: os.path.isfile(path)

<code># non‑existent file
os.path.isfile('C:/Users/wuzhengxiang/Desktop/股票数据分析/pi_01.txt')
False

# existing file
os.path.isfile('C:/Users/wuzhengxiang/Desktop/股票数据分析/pi.txt')
True

# directory (not a file)
os.path.isfile('C:/Users/wuzhengxiang/Desktop/股票数据分析/')
False</code>

29. os.path.isdir()

Description: Checks if the given path points to a directory.

Syntax: os.path.isdir(path)

<code>os.path.isdir('C:/Users/wuzhengxiang/Desktop/股票数据分析')
True

os.path.isdir('C:/Users/wuzhengxiang/Desktop/股票数据分析1')
False

os.path.isdir('C:/Users/wuzhengxiang/Desktop/股票数据分析/pi.txt')
False</code>

30. os.path.join()

Description: Joins one or more path components intelligently.

Syntax: os.path.join(path1, path2, ...)

<code>os.path.join('C:/Users', 'wuzhengxiang/Desktop/', '股票数据分析')
'C:/Users\\wuzhengxiang/Desktop/股票数据分析'

Path1 = 'home'
Path2 = 'develop'
Path3 = 'code'
Path20 = os.path.join(Path1, Path2, Path3)
print('Path20 =', Path20)
# Path20 = home\develop\code</code>

31. os.path.normcase()

Description: Normalizes the case of a pathname (useful on Windows).

Syntax: os.path.normcase(path)

<code>os.path.normcase('D:\\Python\\test\\data.txt')
'd:\\python\\test\\data.txt'

os.path.normcase('c:/WINDOWS\\system64\\')
'c:\\windows\\system64\\'</code>

32. os.path.normpath()

Description: Normalizes a pathname by collapsing redundant separators and up‑level references.

Syntax: os.path.normpath(path)

<code>os.path.normpath('c://windows\\System32\\../Temp/')
'c:\\windows\\Temp'</code>

33. os.path.realpath()

Description: Returns the canonical path of the specified filename, eliminating any symbolic links.

Syntax: os.path.realpath(path)

<code>os.path.relpath('C:\\Users\\Administrat\\代码TRY\\test.ipynb', '代码TRY')
'..\\..\\..\\..\\Administrat\\代码TRY\\test.ipynb'</code>

34. os.path.relpath()

Description: Computes a relative filepath to path from the current directory or an optional start point.

Syntax: os.path.relpath(path[, start])

<code>os.path.relpath('C:/Users/wuzhengxiang/Desktop/股票数据分析\\test.gif')
'test.gif'</code>

35. os.path.samefile()

Description: Determines whether two pathnames refer to the same file or directory.

Syntax: os.path.samefile(path1, path2)

<code>os.path.samefile('C:\\Users', 'C:\\Users')
True

os.path.samefile('C:\\Users', 'C:/Users')
True

os.path.samefile('C:\\Users', 'C:/Users/wuzhengxiang')
False</code>

36. os.path.split()

Description: Splits a pathname into a pair (head, tail) where tail is the last pathname component.

Syntax: os.path.split(path)

<code>os.path.split('D:\\Python\\test\\data.txt')
('D:\\Python\\test', 'data.txt')</code>

37. os.path.splitdrive()

Description: On Windows, splits the pathname into drive and the rest of the path.

Syntax: os.path.splitdrive(path)

<code>os.path.splitdrive('C:/Users/zhengxiang.wzx/IMG_7358.JPG')
('C:', '/Users/zhengxiang.wzx/IMG_7358.JPG')</code>

38. os.path.splitext()

Description: Splits the pathname into a root and extension.

Syntax: os.path.splitext(path)

<code>os.path.splitext('C:/Users/zhengxiang.wzx/IMG_7358.JPG')
('C:/Users/zhengxiang.wzx/IMG_7358', '.JPG')</code>

39. os.path.walk()

Description: Recursively walks a directory tree, calling a user‑provided function for each directory. (Note: In modern Python, os.walk() is preferred.)

Syntax: os.path.walk(path, visit, arg)

<code>list(os.walk('C:/Users/wuzhengxiang/Desktop/股票数据分析'))
[('C:/Users/wuzhengxiang/Desktop/股票数据分析', ['1122'], ['ETF研究.py', 'foo.txt', 'pi.txt', 'render.html', 'test.gif']),
 ('C:/Users/wuzhengxiang/Desktop/股票数据分析\\1122', [], [])]

# Example of collecting all file paths
abs_cur_dir = 'C:/Users/wuzhengxiang/Desktop/股票数据分析'
file_url = []
for dirs, folders, files in os.walk(abs_cur_dir):
    for i in files:
        file_url.append(os.path.join(dirs, i))
print(file_url)
# ['C:/Users/wuzhengxiang/Desktop/股票数据分析\\ETF研究.py', ...]
</code>

- END -

Pythonfilesystemos modulefile operationspath manipulation
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.