← 返回首页
Python3基础教程(五十二)
发表时间:2022-04-19 23:32:03
文件与目录

1.os 模块

如果我们要操作文件、目录,可以使用Python内置的os模块。

操作系统文件目录常用API如下: |函数|说明| |-|-| |os.name|操作系统类型| |os.uname()|获取详细的系统信息(windows不支持)| |os.environ|环境变量| |os.path.abspath('.')|查看当前目录的绝对路径| |os.path.exists(path)|判断路径是否存在| |os.path.join(path, 'subpath')|目录拼接| |os.mkdir(path)|创建目录| |os.path.isfile()|是否是文件| |os.path.isdir()|是否是目录| |os.path.splitext('path')|获取文件扩展名| |os.rmdir(path)|删除空目录| |os.stat(file)|获取文件属性| |os.path.getsize(filename)|获取文件大小| |os.rename(old, new)|文件重命名| |shutil.rmtree(path, ignore_errors=True)|删除非空目录|

实例:

在当前目录下创建 test/xixi/haha.txt 文件后,删除xixi目录。

# -*- coding: utf-8 -*-
# @Time : 2022/4/20 11:35
# @File : osdemo.py
# @Software : PyCharm

import os
import shutil

# 操作系统
print(os.name)
# 注意uname()函数在Windows上不提供
# print(os.uname())

# 查看环境变量
print(os.environ)
# 查看当前目录的绝对路径
print(os.path.abspath('.'))
# 打印当前目录
path = os.path.abspath('.')
# 目录拼接
path = os.path.join(path, 'test')
# 打印拼接后的目录
print(path)

# 判断目录是否存在
if not os.path.exists(path):
    # 创建目录
    os.mkdir(path)

path = os.path.join(path, 'xixi')
print(path)

if not os.path.exists(path):
    os.mkdir(path)

# 创建新文件并且写入
with open(path + '/haha.txt', 'a', encoding='utf-8') as f:
    f.write('hello,world\n')


# os.path.splitext()可以直接让你得到文件扩展名
extendname = os.path.splitext(path + '/haha.txt')
# 打印文件扩展名
print(extendname[1])

# 删除目录,只能删除空目录
# os.rmdir(path)

# 删除非空目录
shutil.rmtree(path, ignore_errors=True)

运行结果:

nt
environ({'WINDIR': 'C:\\Windows', '_OLD_VIRTUAL_PATH': 'C:\\Program Files\\Java\\jdk1.8.0_281\\bin;C:\\Windows\\system32;C:\\Windows;C:\\Windows\\System32\\Wbem;C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;C:\\mysql-8.0.21-winx64\\bin;C:\\apache-maven-3.6.0\\bin;C:\\Program Files\\Python310;C:\\Program Files\\Python310\\Scripts;C:\\Users\\Administrator\\AppData\\Local\\Microsoft\\WindowsApps;C:\\Program Files\\Bandizip\\;%DevEco Studio%;C:\\Users\\Administrator\\AppData\\Local\\Programs\\Microsoft VS Code\\bin', '_OLD_VIRTUAL_PROMPT': '$P$G'})
G:\python_lesson\iodemo
G:\python_lesson\iodemo\test
G:\python_lesson\iodemo\test\xixi
.txt

小结: Python的os模块封装了操作系统的目录和文件操作,要注意这些函数有的在os模块中,有的在os.path模块中。