自编python程序: os模块的应用(文件执行与复制)
(1) .py文件的执行操作
- 代码展示
- 代码如下
import os
def Execute(path):
if os.path.isfile(path) and path.endswith('.py'):
os.system('python %s'% path)
elif os.path.isdir:
for name in os.listdir(path):
new_path=os.path.join(path,name)
os.system('python %s'% new_path)
Execute('C:/Users/Administrator/Desktop/A-Python')
- 运行效果如下
(1) 文件的复制操作
- 代码展示
- 代码如下
import os
def FileCopy(path1,path2):
filename=os.path.basename(path1)
new_path=os.path.join(path2,filename)
if os.path.exists(new_path):
print('已有重名文件')
elif os.path.isfile(path1) and os.path.isdir(path2):
with open(path1,'rb') as f1:
file=f1.read()
with open(new_path,'wb') as f2:
f2.write(file)
print('复制成功')
else:
print('请在第一个位置传入文件路径,第二个位置传入要复制到的文件夹路径')
path1='C:/Users/Administrator/Desktop/A-Python/demo1.py'
path2='C:/Users/Administrator/Desktop'
FileCopy(path1,path2)
- 运行效果如下