Python的OS模块怎么使用

50次阅读
没有评论

共计 562 个字符,预计需要花费 2 分钟才能阅读完成。

OS 模块是 Python 的内置模块,提供了与操作系统交互的功能。下面是一些常见的 OS 模块的使用示例:

  1. 获取当前工作目录:
import os

current_dir = os.getcwd()
print(current_dir)
  1. 创建目录:
import os

os.mkdir("new_directory")
  1. 删除目录:
import os

os.rmdir("directory_to_delete")
  1. 列出目录中的文件和子目录:
import os

contents = os.listdir("directory_path")
for item in contents:
    print(item)
  1. 检查文件或目录是否存在:
import os

exists = os.path.exists("file_or_directory_path")
if exists:
    print("File or directory exists!")
else:
    print("File or directory does not exist!")
  1. 运行操作系统命令:
import os

os.system("command_to_execute")

这只是 OS 模块的一小部分功能示例,还有其他功能,如文件操作、路径操作、环境变量等。你可以查阅 Python 的官方文档或其他教程来获取更多使用方法。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2024-02-05发表,共计562字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)