Python/ target=_blank class=infotextkey>Python 标准库中的 os 模块提供了访问操作系统功能的接口,包括文件和目录操作、进程管理、环境变量、时间等功能。以下是 os 模块的主要功能及其应用场景:
import os
cwd = os.getcwd()
print(cwd)
import os
os.chdir('/home/user/')
import os
files = os.listdir('/home/user/')
print(files)
import os
os.mkdir('/home/user/my_folder')
import os
os.makedirs('/home/user/my_folder/sub_folder')
import os
os.remove('/home/user/my_file.txt')
os.rmdir('/home/user/my_folder')
import shutil
shutil.rmtree('/home/user/my_folder')
import os
path = '/home/user/my_file.txt'
if os.path.isfile(path):
print('This is a file.')
elif os.path.isdir(path):
print('This is a directory.')
import os
path = os.path.join('/home', 'user', 'my_folder', 'my_file.txt')
print(path)
import os
path = 'my_folder/my_file.txt'
abs_path = os.path.abspath(path)
print(abs_path)
import os
path = '/home/user/my_folder/my_file.txt'
basename = os.path.basename(path)
print(basename)
import os
path = '/home/user/my_folder/my_file.txt'
dirname = os.path.dirname(path)
print(dirname)
import os
path = '/home/user/my_folder/my_file.txt'
if os.path.exists(path):
print('This file exists.')
else:
print('This file does not exist.')
import os
path = '/home/user/my_file.txt'
size = os.path.getsize(path)
print(size)
import os
import time
path = '/home/user/my_file.txt'
ctime = os.path.getctime(path)
mtime = os.path.getmtime(path)
print('Created:', time.ctime(ctime))
print('Modified:', time.ctime(mtime))
import os
path = '/home/my_folder/my_file.txt'
if os.path.isabs(path):
print('This is an absolute path.')
else:
print('This is a relative path.')
import os
path = '/home/user/my_folder/my_file.txt'
dirname, basename = os.path.split(path)
print('Directory:', dirname)
print('Filename:', basename)
import os
os.system('ls')
import os
env = os.environ
print(env)
import platform
system = platform.system()
version = platform.version()
print('System:', system)
print('Version:', version)
注意事项:
整理不易欢迎点赞转发收藏,关注我每天分享运维小知识。