5-2 os模块

导入os模块

 1 import os
 2 
 3 res = os.listdir('D:\study')  # 列出某个目录下的所有文件
 4 
 5 os.remove('newuser.json')  # 删除某个目录下的某个文件
 6 
 7 os.rename('test','test2')  # 重命名某个路径下的某个文件
 8 
 9 os.makedirs(r'test1/lyl/aaa')  # 当父目录不存在时,会创建父目录
10 
11 # 当父目录不存在的时候,会报错
12 # FileNotFoundError: [WinError 3] 系统找不到指定的路径。: 'test/niuhy/haha'
13 os.mkdir(r'test1/lyl/aaa/111')  # 创建文件夹,当文件路径不存在的时候,会报错
14 
15 
16 # 判断一个文件是否存在 True False
17 res = os.path.exists(r'D:\my-python\day5\email.txt')
18 print(res)
19 
20 print(os.path.isfile('test1'))  # 判断是否为文件  False
21 
22 print(os.path.isdir('test1') )# 判断是否为文件  True
23 
24 # 将路径和文件进行分割
25 # ('D:\\my-python\\day5\\test1\\lyl\\aaa\\111', 'email.txt')
26 res = os.path.split(r'D:\my-python\day5\test1\lyl\aaa\111\email.txt')
27 print(res)
28 
29 res = os.path.dirname(r'\my-python\day5') # 取父目录
30 print(res)
31 
32 # 获取当前的目录  D:\my-python\day5
33 print(os.getcwd())
34 
35 # 更改当前目录
36 os.chdir(r'D:\my-python\day5\test1')
37 
38 # 查看当前的目录  # 更改当前目录
39 print(os.getcwd())
40 
41 # 打开a.txt文件,如果不存在就创建
42 open('a.txt','w')
43 
44 # # 查看环境变量
45 print(os.environ)
46 
47 # 拼接路径 test\hhh\abc\a.txt
48 res = os.path.join('test','hhh','abc','a.txt')
49 print(res)
50 
51 # 根据相对路径取绝对路径  D:\my-python
52 # . 当前路径  .. 上一级路径
53 res= os.path.abspath('..')
54 print(res)
55 
56 # 执行操作系统命令
57 res = os.system('ipconfig') 
58 print(res)
59 
60 res = os.popen('ifconfig').read()
61 print('res',res)

猜你喜欢

转载自www.cnblogs.com/hushaoyan/p/10061682.html
5-2