Python模块os的系统函数

Python模块os的系统函数

用open()创建文件
用exists()检查文件是否存在
用isfile()检查是否为文件
用copy()复制文件(shutil模块)
用rename()重命名文件
用硬链接link()或者符号链接symlink()创建链接,islink()判断是符号链接还是文件,
用chmod()修改权限
用chown()修改所有者
用abspath()获取路径名
用realpath()获取符号的路径名
用remove()删除文件

# _*_coding:utf-8_*_
fout = open('oops.txt', 'wt')
print('Oops, I created a file.', file= fout)
fout.close()
import os
print(os.path.exists('oops.txt'))
print(os.path.exists('./oops.txt'))
name = 'oops.txt'
print(os.path.isfile(name))
print(os.path.isdir(name))
print(os.path.isdir('.'))   #'.'表当前目录,'..'表上层目录
print(os.path.isabs(name))  #判断是否为绝对路径名
import shutil
shutil.copy('oops.txt', 'ohno.txt') #shutil.move()会复制一个文件并删除原文件
os.rename('ohno.txt', 'ohwell.txt')
os.link('oops.txt', 'yikes.txt')
print(os.path.isfile('yikes.txt'))
print(os.path.islink('yikes.txt'))
os.symlink('oops.txt', 'jeepers.txt')   #这方法我运行出错了,需要管理员权限才行
os.path.islink('jeepers.txt')
os.chmod('oops.txt', 0o400) #八进制
#包含用户,用户组和其他用户组的读写执行(100读,010写,001执行)
uid = 5
gid = 22
os.chrown('oops', uid, gid)
print(os.path.abspath('oops.txt'))
print(os.path.realpath('jeepers.txt'))
os.remove('oops.txt')
print(os.path.exists('opps.txt'))

结果:
True
True
True
False
True
False
Traceback (most recent call last):
  File "D:/MyPython/PycharmProjects/example/test2.py", line 19, in <module>
    os.symlink('oops.txt', 'jeepers.txt')
OSError: symbolic link privilege not held
True
False

目录

使用mkdir()创建目录
使用rmdir()删除目录
使用listdir()列出目录
使用chdir()修改当前目录
使用glob()列出匹配文件:不是正则表达式
*:  会匹配任何名称
?:  会匹配一个字符
[abc]:  会匹配a|b|c
[!abc]:  除了a,b,c之外的所有字符

# _*_coding:utf-8_*_
import os
os.mkdir('poems')
print(os.path.exists('poems'))
os.rmdir('poems')
print(os.path.exists('poems'))
os.mkdir('poems')
os.listdir('poems')
os.mkdir('poems/mcintyre')
os.listdir('poems')
os.chdir('poems')   #从当前目录跳转到poems目录
print(os.listdir('.'))

import glob
print(glob.glob('m*'))
print(glob.glob('??'))
print(glob.glob('m??????e'))
print(glob.glob('[klm]*e'))

结果:
True
False
['mcintyre']
['mcintyre']
[]
['mcintyre']
['mcintyre']

程序和进程

# _*_coding:utf-8_*_
import os
print(os.getpid())  #正在运行的Python解释器的进程号
print(os.getcwd())  #当前的工作目录
#windows没有下面两个方法
#print(os.getuid())  #用户ID
#print(os.getgid())  #用户组ID

使用subprocess创建进程(单进程)

只能在shell中运行其他程序并获取它的输出,这里获取dir程序的输出
# _*_coding:utf-8_*_
import subprocess
ret = subprocess.getoutput('dir')
print(ret)
ret =subprocess.getoutput('dir -u')
print(ret)
ret = subprocess.getstatusoutput('dir')
print(ret)

结果:
 驱动器 D 中的卷是 软件
 卷的序列号是 0008-5846

 D:\MyPython\PycharmProjects\example 的目录

2018/01/25  09:22    <DIR>          .
2018/01/25  09:22    <DIR>          ..
2018/01/24  16:30    <DIR>          .idea
2018/01/24  13:01               128 home.wsgi
2018/01/23  19:54                46 index.html
2018/01/24  15:25                25 oops.txt
2018/01/24  15:37    <DIR>          poems
2018/01/23  21:01    <DIR>          templates
2018/01/25  09:22               190 test2.py
2018/01/22  08:45    <DIR>          venv
2018/01/24  15:25                25 yikes.txt
               5 个文件            414 字节
               6 个目录 85,046,190,080 可用字节
 驱动器 D 中的卷是 软件
 卷的序列号是 0008-5846

 D:\MyPython\PycharmProjects\example 的目录

找不到文件
(0, ' 驱动器 D 中的卷是 软件\n 卷的序列号是 0008-5846\n\n D:\\MyPython\\PycharmProjects\\example 的目录\n\n2018/01/25  09:22    <DIR>          .\n2018/01/25  09:22    <DIR>          ..\n2018/01/24  16:30    <DIR>          .idea\n2018/01/24  13:01               128 home.wsgi\n2018/01/23  19:54                46 index.html\n2018/01/24  15:25                25 oops.txt\n2018/01/24  15:37    <DIR>          poems\n2018/01/23  21:01    <DIR>          templates\n2018/01/25  09:22               190 test2.py\n2018/01/22  08:45    <DIR>          venv\n2018/01/24  15:25                25 yikes.txt\n               5 个文件            414 字节\n               6 个目录 85,046,190,080 可用字节')

Process finished with exit code 0

使用multiprocessing创建进程

一个程序中运行多个进程,Process()函数会创建一个新进程来运行do_this()函数,由于循环,创建了四个。当你需要多进程来减少运行时间可以用,支持任务队列和进程间的通信。
# _*_coding:utf-8_*_
import multiprocessing
import os
def do_this(what):
    whoami(what)
def whoami(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 function %s" % n,))
        p.start()

结果:
Process 15536 says: I'm the main program
Process 14900 says: I'm function 0
Process 15472 says: I'm function 1
Process 15748 says: I'm function 2
Process 14512 says: I'm function 3


使用terminate()终止进程

# _*_coding:utf-8_*_
import multiprocessing
import os
import time

def whoami(name):
    print("I'm %s, in process %s" % (name, os.getpid()))
def loopy(name):
    whoami(name)
    start = 1
    stop = 1000000
    for num in range(start, stop):
        print("\tNumber %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()
    
结果:
I'm main, in process 15988
I'm loopy, in process 5496
   Number 1 of 1000000.Honk!
   Number 2 of 1000000.Honk!
   Number 3 of 1000000.Honk!
   Number 4 of 1000000.Honk!
   Number 5 of 1000000.Honk!

日期和时间

datetime模块(四个主要的对象):
date处理年月日
time处理时分秒和微妙
datetime处理日期和时间同时出现的情况
timedelta处理日期和/或者时间间隔

# _*_coding:utf-8_*_
from datetime import date
from datetime import timedelta
halloween = date(2014,10,31)
print(halloween)
print(halloween.day)
print(halloween.month)
print(halloween.year)
print(halloween.isoformat())    #iso指ISO8601,时间的国际标准,年月日
now = date.today()
print(now)
one_day = timedelta(days=1)
tomorrow = now + one_day
print(tomorrow)
print(now + 17 * one_day)
yesterday = now - one_day
print(yesterday)

结果:
2014-10-31
31
10
2014
2014-10-31
2018-01-25
2018-01-26
2018-02-11
2018-01-24

# _*_coding:utf-8_*_
from datetime import datetime
from datetime import time
from datetime import date
noon = time(12, 0, 0)
print(noon)
print(noon.hour)
print(noon.minute)
print(noon.second)
print(noon.microsecond)
some_day = datetime(2014,1,2,3,4,5,6)
print(some_day)
print(some_day.isoformat())
now = datetime.now()
print(now)
print(now.microsecond)
#可以用combine()方法把一个date对象和一个time对象合并成一个datetime对象:
noon = time(12)
this_day = date.today()
noon_today = datetime.combine(this_day, noon)
print(noon_today)
#也可以从datetime中取出date和time部分
print(noon_today.date())
print(noon_today.time())


结果:
12:00:00
12
0
0
0
2014-01-02 03:04:05.000006
2014-01-02T03:04:05.000006
2018-01-25 10:05:28.192590
192590
2018-01-25 12:00:00
2018-01-25
12:00:00

使用time模块

time()函数返回当前时间的纪元值(Unix时间使用的是从1970年1月1日0点开始的描述):
# _*_coding:utf-8_*_
import time
now = time.time()
print(now)
print(time.ctime(now))  #把一个纪元值转换成一个字符串
#要想转换成真正的日期,可以用struct_time对象,
# #localtime()会返回当前系统时区下的时间,getime()会返回UTC时间
print(time.localtime(now))
print(time.gmtime(now))
#把struct_time对象转换成纪元值
tm = time.localtime(now)
print(time.mktime(tm))

结果:
1516846610.66223
Thu Jan 25 10:16:50 2018
time.struct_time(tm_year=2018, tm_mon=1, tm_mday=25, tm_hour=10, tm_min=16, tm_sec=50, tm_wday=3, tm_yday=25, tm_isdst=0)
time.struct_time(tm_year=2018, tm_mon=1, tm_mday=25, tm_hour=2, tm_min=16, tm_sec=50, tm_wday=3, tm_yday=25, tm_isdst=0)
1516846610.0

读取日期和时间

strftime()的格式化字符串
格式化字符串  日期/时间单元 范围
%Y              年           1900-...
%m              月           01-12
%B              月名         January...
%b              月名缩写     Jan...
%d              日           01-31
%A              星期         Sunday...
%a              星期缩写     Sun...   
%H              时(24小时) 00-23
%I              时(12小时) 01-12
%p              上午/下午    AM,PM
%M              分           00-59
%S              秒           00-59
# _*_coding:utf-8_*_
import time
fmt = "It's %A, %B %d, %Y, local time %I:%M:%S%p"
t = time.localtime()
print(t)
print(time.strftime(fmt, t))
from datetime import date
#date对象只能获取日期部分,时间默认是午夜
some_day = date(2018,2,1)
print(some_day.strftime(fmt))
#对于time对象,只能转换时间部分
from datetime import time
some_time= time(10,32)
print(some_time.strftime(fmt))

结果:
time.struct_time(tm_year=2018, tm_mon=1, tm_mday=25, tm_hour=10, tm_min=33, tm_sec=50, tm_wday=3, tm_yday=25, tm_isdst=0)
It's Thursday, January 25, 2018, local time 10:33:50AM
It's Thursday, February 01, 2018, local time 12:00:00AM
It's Monday, January 01, 1900, local time 10:32:00AM


字符串转换日期或者时间
 
# _*_coding:utf-8_*_
import time
fmt = "%Y-%m-%d"
print(time.strptime("2012-1-29", fmt))
print(time.strptime("2012-13-29", fmt))     #月份超出会报错

结果:
Traceback (most recent call last):
  File "D:/MyPython/PycharmProjects/example/test2.py", line 5, in <module>
    print(time.strptime("2012-13-29", fmt))     #超出会报错
  File "D:\Python36\Lib\_strptime.py", line 559, in _strptime_time
time.struct_time(tm_year=2012, tm_mon=1, tm_mday=29, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=29, tm_isdst=-1)
    tt = _strptime(data_string, format)[0]
  File "D:\Python36\Lib\_strptime.py", line 362, in _strptime
    (data_string, format))
ValueError: time data '2012-13-29' does not match format '%Y-%m-%d'

在shell程序中,locale设置是操作系统中的国际化设置,打印不同的月和日名称,可以通过setlocale()修改

# _*_coding:utf-8_*_
import locale
from datetime import date
halloween = date(2014,10,31)
#美国语言,法语,德语,西班牙语,冰岛语
for lang_country in ['en_us','fr_fr','de_de','es_es','is_is',]:
    print(locale.setlocale(locale.LC_TIME, lang_country))
    print(halloween.strftime('%A, %B %d'))


# _*_coding:utf-8_*_
import locale
names = locale.locale_alias.keys()  #获取所有的lang_country值
good_names = [name for name in names if len(name) == 5 and name[2] == '_']
print(good_names)
de = [name for name in good_names if name.startswith('de')] #获取所有德国语言
print(de)

结果:
['a3_az', 'aa_dj', 'aa_er', 'aa_et', 'af_za', 'am_et', 'an_es', 'ar_aa', 'ar_ae', 'ar_bh', 'ar_dz', 'ar_eg', 'ar_in', 'ar_iq', 'ar_jo', 'ar_kw', 'ar_lb', 'ar_ly', 'ar_ma', 'ar_om', 'ar_qa', 'ar_sa', 'ar_sd', 'ar_sy', 'ar_tn', 'ar_ye', 'as_in', 'az_az', 'be_by', 'bg_bg', 'bn_bd', 'bn_in', 'bo_cn', 'bo_in', 'br_fr', 'bs_ba', 'ca_ad', 'ca_es', 'ca_fr', 'ca_it', 'cs_cs', 'cs_cz', 'cv_ru', 'cy_gb', 'cz_cz', 'da_dk', 'de_at', 'de_be', 'de_ch', 'de_de', 'de_lu', 'dv_mv', 'dz_bt', 'ee_ee', 'el_cy', 'el_gr', 'en_ag', 'en_au', 'en_be', 'en_bw', 'en_ca', 'en_dk', 'en_gb', 'en_hk', 'en_ie', 'en_in', 'en_ng', 'en_nz', 'en_ph', 'en_sg', 'en_uk', 'en_us', 'en_za', 'en_zm', 'en_zw', 'eo_eo', 'eo_xx', 'es_ar', 'es_bo', 'es_cl', 'es_co', 'es_cr', 'es_cu', 'es_do', 'es_ec', 'es_es', 'es_gt', 'es_hn', 'es_mx', 'es_ni', 'es_pa', 'es_pe', 'es_pr', 'es_py', 'es_sv', 'es_us', 'es_uy', 'es_ve', 'et_ee', 'eu_es', 'eu_fr', 'fa_ir', 'ff_sn', 'fi_fi', 'fo_fo', 'fr_be', 'fr_ca', 'fr_ch', 'fr_fr', 'fr_lu', 'fy_de', 'fy_nl', 'ga_ie', 'gd_gb', 'gl_es', 'gu_in', 'gv_gb', 'ha_ng', 'he_il', 'hi_in', 'hr_hr', 'ht_ht', 'hu_hu', 'hy_am', 'ia_fr', 'id_id', 'ig_ng', 'ik_ca', 'in_id', 'is_is', 'it_ch', 'it_it', 'iu_ca', 'iw_il', 'ja_jp', 'jp_jp', 'ka_ge', 'kk_kz', 'kl_gl', 'km_kh', 'kn_in', 'ko_kr', 'ks_in', 'ku_tr', 'kw_gb', 'ky_kg', 'lb_lu', 'lg_ug', 'li_be', 'li_nl', 'lo_la', 'lt_lt', 'lv_lv', 'mg_mg', 'mi_nz', 'mk_mk', 'ml_in', 'mn_mn', 'mr_in', 'ms_my', 'mt_mt', 'my_mm', 'nb_no', 'ne_np', 'nl_aw', 'nl_be', 'nl_nl', 'nn_no', 'no_no', 'nr_za', 'ny_no', 'oc_fr', 'om_et', 'om_ke', 'or_in', 'os_ru', 'pa_in', 'pa_pk', 'pd_de', 'pd_us', 'ph_ph', 'pl_pl', 'pp_an', 'ps_af', 'pt_br', 'pt_pt', 'ro_ro', 'ru_ru', 'ru_ua', 'rw_rw', 'sa_in', 'sc_it', 'sd_in', 'sd_pk', 'se_no', 'sh_hr', 'sh_sp', 'sh_yu', 'si_lk', 'sk_sk', 'sl_cs', 'sl_si', 'so_dj', 'so_et', 'so_ke', 'so_so', 'sp_yu', 'sq_al', 'sq_mk', 'sr_cs', 'sr_me', 'sr_rs', 'sr_sp', 'sr_yu', 'ss_za', 'st_za', 'sv_fi', 'sv_se', 'sw_ke', 'sw_tz', 'ta_in', 'ta_lk', 'te_in', 'tg_tj', 'th_th', 'ti_er', 'ti_et', 'tk_tm', 'tl_ph', 'tn_za', 'tr_cy', 'tr_tr', 'ts_za', 'tt_ru', 'ug_cn', 'uk_ua', 'ur_in', 'ur_pk', 'uz_uz', 've_za', 'vi_vn', 'wa_be', 'wo_sn', 'xh_za', 'yi_us', 'yo_ng', 'zh_cn', 'zh_hk', 'zh_sg', 'zh_tw', 'zu_za']
['de_at', 'de_be', 'de_ch', 'de_de', 'de_lu']



本文是我在学习了丁嘉瑞的《Python语言及其应用》所做的笔记,只用于学习。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值