首页 > 技术文章 > python——os平台编程

ruo-li-suo-yi 2017-09-02 17:18 原文

一、os平台编程需求

1、目录文件的操作

对系统目录,文件的操作方法

2、程序的定时执行

3、可执行程序的转换

python程序向可执行程序的转换

二、目录文件操作

 

root:当前目录;

dirs:当前目录下的文件夹

files:当前目录下的文件名

 

1 import os
2 path =input("路径:")
3 for root,dirs,files in os.walk(path):
4         print(root,"\n")
5         print(dirs,"\n")
6         print(files,"\n")

 

1 import os
2 path =input("路径:")
3 for a in os.walk(path):
4         print(a[0],"\n")
5         print(a[1],"\n")
6         print(a[2],"\n")

 

以下程序返回绝对路径

1 import os
2 path =input("路径:")
3 for root,dirs,files in os.walk(path):
4         for name in files:
5                 print(os.path.join(root,name) 

 

 

更改名字,所有名字加了_ok。

1 import os
2 path=input("路径:")
3 for root,dirs,files in os.walk(path):
4     for name in files:
5         fname,fext=os.path.splitext(name)
6         os.rename(os.path.join(root,name),os.path.join(root,fname+"_ok"+fext))
7         print(name)

三、定时执行程序

delay:延长多少时间执行

priority:执行优先级

action:执行具体功能

argument:需要的参数

 1 import sched, time
 2   
 3 def print_time():
 4     print("From print_time", time.time()) 
 5 def print_some_times():
 6     print (time.time())
 7 
 8 s = sched.scheduler(time.time, time.sleep) # 生成调度器
 9 print(time.time())
10 s.enter(5, 1, print_time, ()) 
11 # 加入调度事件
12 # 四个参数分别是:
13 # 间隔事件(具体值决定与delayfunc, 这里为秒);
14 # 优先级(两个事件在同一时间到达的情况);
15 # 触发的函数;
16 # 函数参数;
17 s.enter(10, 1, print_time, ())
18 
19 # 运行
20 s.run()
21  
22 if __name__ == '__main__':
23     print_some_times()

之间相差5秒,确定了多线程的执行顺序。

 

 1 import sched,time
 2 
 3 def print_time(msg="default"):
 4     print("当前时间",time.time(),msg)
 5 
 6 def time_other():
 7     print("优先度2",time.time())
 8 
 9 print(time.time())
10 
11 s=sched.scheduler(time.time,time.sleep)
12 
13 s.enter(10,1,print_time,())
14 s.enter(5,1,print_time,())
15 s.enter(5,2,time_other,())
16 s.run()
17 
18 print(time.time())

 

 

四、可执行程序的转换

第三步注意,一定要在同一个路径下

 

 

 首先应该安装pyinstaller库

但是该库目前不支持python3.6,所以结果如下

 

 

 

 

 

 

推荐阅读