1 import os
2 import os.path
3 print(os.path.basename('/Users/c2apple/Desktop/彩屏')) #获取路径的最后一个组成部分
4 os.path.exists('test1.txt') #测试文件是否存在
5 os.rename('data.txt','sample1.txt') #os.renamme()可以实现文件的改名和移动
6 print(os.path.exists('shelve_test.dat.db'))
7 path1='D//mypython_exp//new_test.txt'
8 print(os.path.dirname(path1))
9 print(os.path.split(path1)) #切分文件路径和文件名
10 print(os.path.splitdrive(path1)) #切分文件扩展名
11 print(os.getcwd()) #返回当前工作目录
12 print(os.mkdir(os.getcwd()+'//temp')) #创建目录
13 os.mkdir(os.getcwd()+'//temp1') #改变当前目录
14 print(os.getcwd())
15 print(os.mkdir((os.getcwd()+'//test1')))
16 print(os.path.commonpath([r'C:\windows\notepad.exe',r'C:\windows\ssysstem']))
17 os.rmdir('temp')
18 import shutil #导入shutil模块
19 shutil.copyfile('dir.txt','dir1.txt') #复制文件
20
21 import os
22 import stat
23 import shutil
24 def remove_readonly(func,path,_): #定义回调函数
25 os.chmod(path,stat.S_IWRITE) #删除文件的只读属性
26 func(path)
27 shutil.rmtree('/Users/c2apple/Desktop/xx文件夹',onerror=remove_readonly) #删除某只读文件夹
28 #用递归复制文件夹,并忽略扩展名为pyc的文件和以'新'开头的文件和子文件夹:
29 from shutil import copytree,ignore_patterns
30 #copytree('/Users/c2apple/Documents/pythonTest','/Users/c2apple/Documents/pythonTest/pythonTest2',ignore_patterns('*','pyc','新'))
31
32 '''
33 如果需要遍历指定目录下的所有子目录和文件,可以使用递归的方法
34 '''
35 import os
36 def visitDir(path): #path为路径,具体以文件路径为主,示例中路径为'/Users/c2apple/Documents/pythonTest'
37 if not os.path.isdir(path):
38 print('Error:',path,'"is not a directory or does not exist')
39 return
40 for lists in os.listdir(path):
41 sub_path=os.path.join(path,lists)
42 print(sub_path)
43 if os.path.isdir(sub_path):
44 visitDir(sub_path) #递归调用
45 visitDir('/Users/c2apple/Documents/pythonTest')
46
47 '''
48 使用os模块的walk()方法进行指定目录的遍历
49 '''
50 import os
51 def visitDir2(path):
52 if not os.path.isdir(path):
53 print('Error:',path,'"iss not a directory or does not exits.')
54 return
55 list_dirs=os.walk(path)
56 for root,dirs,files in list_dirs: #遍历该元组的目录和文件信息
57 for d in dirs:
58 print(os.path.join(root,d)) #获取完整路径
59 for f in files:
60 print(os.path.join(root,f)) #获取文件的绝对路径
61 visitDir2('/Users/c2apple/Documents/pythonTest')
62
63 '''
64 os模块除了用于文件操作和文件的方法之外,os模块还是提供了大量其他方法。例如,system()方法可以用来执行外部程序或系统内置命令,popen()和
65 startfile()也可以用来启动外部程序。另外,Python标准库subbprocess也提供了大量与进程创建与管理有关的对象,pywin32工具包提供的ShellExecute()
66 和CreateProcess()函数,这些对象和函数也可以实现启动外部程序的目的,如果对Python标准库ctypes和系统API函数熟悉,也可以直接调用底层API函数
67 实现更加高阶的功能
68 '''
69 import subprocess
70 h=subprocess.Popen('',executable='C:\\windows\\notepad.exe') #打开记事本程序
71 h.terminate() #结束进程
72 h=subprocess.Popen('',executable='C:\\windows\\notepad.exe') #打开记事本程序
73 h.kill() #结束进程
74 h=subprocess.Popen('',executable='C:\\windows\\notepad.exe') #打开记事本程序
75 import os
76 os.startfile(r'C:\\windows\\notepad.exe') #打开记事本程序
77 os.startfile(r'test.py') #执行Python程序