1、文件
open()代开文件或者创建文件
fout=open('oops.txt','wt')print('Oops, I created a file.',file=fout)
fout.close()
exists()检查文件是否存在,传入相对或者绝对路径
importos>>>os.path.exist('oops.txt')
True>>>os.path.exist('./oops.txt')
True>>>os.path.exist('.')
True>>>os.path.exist('..')
True
isfile()、isdir()、isabs()检查是否为文件、目录
>>>os.path.isfile('oops.txt')
True>>>os.path.isdir(.) #当前目录
True>>>os.path.isdir(..) #上层目录
True>>>os.path.isabs('oops.txt') #判断绝对路径
False
copy()、move()复制文件
importshutil>>>shutil.copy('oops.txt','ohno.txt') #复制不删除原文件
>>>shutil.move('oops.txt','ohno.txt') #复制并删除原文件
rename()重命名
>>>os.rename('ohno.txt','ohwell.txt')
link()、symlink()、islink()创建硬链接、符号链接、判断符号链接
>>>os.link('oops.txt','yikes.txt')>>>os.path.isfile('yikes.txt')
True>>>os.path.islink('yikes.txt')
False>>>os.symlink('oops.txt','jeepers.txt')>>>os.path.islinl('jeepers.txt')
True
chmod()修改权限,接受一个八进制值,包含用户、用户组、权限。Unix系统。
>>>os.chmod('oops.txt',0o400) #只能被拥有者读
imprt stat>>>os.chmod('oops.txt',stat.S_IRUSR)
chown()修改所有者。Unix/Linux/Mac系统。
uid=5gid=22
>>>os.chown('oops.txt',uid,gid) #指定用户ID和用户组ID
abspath()获取绝对路径名
>>>os.path.abspath('oops.txt')'/usr/gg/oops.txt'
realpath()获取符号链接对应文件的绝对路径。
>>>os.path.realpath('jeepers.txt')'/usr/gg/oops.txt'
remove()删除文件
>>>os.remove('oops.txt')>>>os.path.exists('oops.txt')
False
2、目录
mkdir()创建目录
>>>os.mkdir('poems')>>>os.path.exists('poems')
True
rmdir()删除目录
>>>os.rmdir('poems')>>>os.path.exists('poems')
False
listdir()列出目录内容
>>>os.mkdir('poems')>>>os.listdir('opems')
[]>>>os.mkdir('opems/mm')>>>os.listdir('poems')
['mm']
chdir()修改当前目录
>>>os.chdir('poems')>>>os.listdir('.')
['mm']
glob()列出匹配文件
*匹配任意名称(re中是.*)
?匹配一个字符
[abc]匹配字符a、b、c
[!abc]匹配除a、b、c之外的字符
importglob>>>glob.glob('m*') #获取以m开头的文件和目录
['mm']>>>glob.glob('?')#获取名称为1个字符的文件和目录
[]>>>glob.glob('m?m') #获取名称为3个字符并且以m开头和结尾的文件和目录
[]>>>glob.glob('[abm]*m')#获取所有以a、b、m开头并且以m结尾的文件和目录
['mm']
3、程序和进程
当运行一个程序时,系统会创建一个进程。该进程会使用系统资源(CPU、内存和磁盘空间)和惭怍系统内核中的数据结构(文件、网络连接、用量统计等)。进程之间互相隔离,一个进程无法访问其他进程的内容,也无法操作其他进程。
操作系统会跟踪所有正在运行的进程,给每个进程一个时间片,结束后切换到其他进程。
os.getpid() #获取正在运行的python解释器的进程号
os.getcwd() #获取正在运行的python解释器的当前工作目录
os.getuid() #获取用户ID
os.getgid() #获取用户组ID
使用subprocess模块启动和终止程序。
importsubprocess
ret=subprocess.getoutput('date')#获取Unix date程序的输出,返回字符串
ret=subprocess.getoutput('date -u')#使用参数
ret=subprocess.getoutput('date -u| wc')#使用管道传给wc命令
check_output()接受一个命令命令和参数列表,返回字节类型输出。
ret=subprocess.check_output(['date','-u'])
getstatusoutput()获取其他程序的退出状态,返回一个包含状态码和输出的元组
ret=subprocess.getstatusoutput('date')
call()退出状态
ret=subprocess.call('date')
ret2=subprocess.call('date -u',shell=True) #调用shell
ret3=subprocess.call(['date','-u'])
使用multiprocessing模块运行多进程
importmultiprocessingimportosdefdo_this(what):
whoami(what)defwhoami(what):print('Process %s says: %s.'%(os.getpid(),what))if __name__=='__main__':
whoami('I'm the main program')
for n in range(4):
p=multiprocessing.Process(target=do_this,args=("I'm the function %s"%n,))
p.start()
使用terminate()终止进程
importmultiprocessingimporttimeimportosdefwhoami(name):print("I'm %s, in process %s."%(name,os.getpid()))defloopy(name):
whoami(name)
start=1stop=1000000
for num inrange(start,stop):print(" Number %s of %s. Honk!"%(num,stop))
time.sleep(1)if __name__=="__main__’:
whoami('main')
p=multiprocessing.Process(target=loopy,args=("loopy",))
p.start()
time.sleep(5)
p.terminate()
4、日期和时间
isleap()检验闰年
importcalendar>>>calendar.isleap(1900)
False>>>calendar.isleap(2000)
True
datetime模块:
date处理年月日
time处理时分秒、微秒
datetime处理日期和时间同时出现的情况
timedelta处理日期和/或时间间隔
创建date对象.date范围从1-1-1到9999-12-31.
import datetime importdate
t1=date(2014,10,31)>>>t1.day31
>>>t1.month10
>>>t1.year2014
>>>t1.isoformat()#ISO 8601标准
'2014-10-31'
today()生成今天日期
now=date.today()
使用timedelta对象实现date加法
from datetime importdate,timedelta
one_day=timedelta(days=1)
tomorrow=now+one_day
yesterday=now-one_day
创建time对象
from datetime importtime
noon=time(12,0,0)>>>noon.hour12
>>>noon.minute
0>>>noon.second
0>>>noon.microsecond
0
创建datetime对象
from datetime importdatetime
some_day=datetime(2014,1,2,3,4,5,6)>>>some_day.isoformat()'2014-01-02T03:04:05.000006'now=datetime.now()
combine()将一个date对象和一个time对象合并为一个datetime对象。
from datetime importtime,date,datetime
noon=time(12)
this_day=date.today()
noon_today=datetime.combine(this_day,noon)>>>noon_today.date()>>>noon_today.time()
使用time模块
time()
importtime
now=time.time() #从1970.1.1零点开始的秒数(纪元值)
>>>time.ctime(now) #转换为字符串,包含年月日星期时分秒
localtime()返回当前系统时区下时间,gmtime()返回UTC时间,两者返回struct_time对象。使用mktime()函数可以将struct_time对象转为纪元值,但是只能精确到秒。
now=time.time()
t1=time.localtime(now)
t2=time.gmtime(now)>>>time.mktime(t1)
读写日期和时间
strftime()把日期和时间转换为字符串,该方法在datetime、date、time对象里有,time模块也有。
%Y:年,范围:1900-...
%m:月,范围:01-12
%B:月名
%b:月名缩写
%A:星期
%a:星期缩写
%H:时,24小时制,00-23
%I:时,12小时制,01-12
%p:上午/下午,AM/PM
%M:分,00-59
%S:秒,00-59
数字左侧补零。
importtime
fmt="It's %A, %B %d, %Y, local time %I:%M:%S%p"t=time.localtime()>>>time.strftime(fmt,t)
date对象的strftime()函数只能获取日期部分,时间默认为午夜;time对象的strftime()函数只会转换时间部分,日期为1900-1-1.
将字符串转为日期或时间,可以用strptime()函数。字符串的非格式化部分必须完全匹配,需要带有破折号分隔。返回一个struct_time对象。
importtime
fmt="%Y-%m-%d"
>>>time.strptime("2012-01-29",fmt)
setlocal()修改不同国家语言的月和日名称。
第一个参数为日期,第二个参数为结合语言和国家名称的缩写字符串。可以用local.local_alias.keys()获取所有值。
importlocalefrom datetime importdate
tt=date(2014,10,31)for lang_country in ['en_us','fr_fr','de_de','es_es','is_is']:print(locale.setlocale(local.LC_TIME,lang_country))print(tt.strftime('%A,%B %d'))
names=locale.locale_alias.keys()
good_names=[name for name in names if len(name)==5 and name[2]=='_']#获取特定格式的缩写
de=[name for name in good_names if name.startwith('de')]#获取德国语言