Python中与操操作系统相关的函数

360影视 2025-02-09 21:20 2

摘要:import os# Craft a path compatible with the underlying OSpath = os.path.join('mystic', 'forest', 'artifact.txt')# Retrieve the tom

制作和剖析路径,确保跨领域(操作系统)兼容性:

import os# Craft a path compatible with the underlying OSpath = os.path.join('mystic', 'forest', 'artifact.txt')# Retrieve the tome's directorydirectory = os.path.dirname(path)# Unveil the artifact's nameartifact_name = os.path.basename(path)

揭示神秘目录中的所有实体:

import oscontents = os.listdir('enchanted_grove')print(contents)

在文件系统的结构中创建新的目录:

import os# create a single directoryos.mkdir('alchemy_lab')# create a hierarchy of directoriesos.makedirs('alchemy_lab/potions/elixirs')

删除文件或目录,抹去其本质:

import os# remove a Fileos.remove('unnecessary_scroll.txt')# remove an empty directoryos.rmdir('abandoned_hut')# remove a directory and its contentsimport shutilshutil.rmtree('cursed_cavern')

直接从 Python 调用 shell 的古老力量:

import subprocess# Invoke the 'echo' incantationresult = subprocess.run(['echo', 'Revealing the arcane'], capture_output=True, text=True)print(result.stdout)

读取并写入虚幻的环境变量:

import os# Read the 'PATH' variablepath = os.environ.get('PATH')# Create a new environment variableos.environ['MAGIC'] = 'Arcane'

将您的存在转移到文件系统中的另一个目录:

import os# Traverse to the 'arcane_library' directoryos.chdir('arcane_library')

辨别路径及其性质的存在——无论是文件还是目录:

import os# Check if a path existsexists = os.path.exists('mysterious_ruins')# Ascertain if the path is a directoryis_directory = os.path.isdir('mysterious_ruins')# Determine if the path is a fileis_file = os.path.isfile('ancient_manuscript.txt')

召唤临时文件和目录,短暂而转瞬即逝:

import tempfile# Create a temporary filetemp_file = tempfile.NamedTemporaryFile(delete=False)print(temp_file.name)# Erect a temporary directorytemp_dir = tempfile.TemporaryDirectoryprint(temp_dir.name)import osimport platform# Discover the operating systemos_name = os.name # 'posix', 'nt', 'java'# Unearth detailed system informationsystem_info = platform.system # 'Linux', 'Windows', 'Darwin'

来源:自由坦荡的湖泊AI

相关推荐