文件操作

python中常用于文件处理的模块有os,shutil等。

1 创建文件

文件的创建可以使用open()函数,如下创建一个test_file.txt的文件:

>>> with open('/Users/xxx/test_file.txt','wt') as f_obj:
... print("This is the content from the test file---John",file=f_obj)
...
>>>

执行完后,可以找到该文件/Users/xxx/test_file.txt

2 判断文件是否存在

判断文件是否存在可以使用os模块的exists()函数,如下:

>>> import os
>>> os.path.exists('/Users/xxx/test_file.txt1')
False
>>> os.path.exists('/Users/xxx/test_file.txt')
True
>>> os.path.exists('/Users/xxx')
True
>>> os.path.exists('/Users/xxx')
False

exists()函数也可以判断目录是否存在。

3 检查是否为文件

可以使用os 模块中的isfile()来检查是否是文件,如下:

>>> os.path.isfile('/Users/xxx')
False
>>> os.path.isfile('/Users/xxx/test_file.txt')
True
>>>

4 文件复制

使用shutil模块中的copy()/remove()函数可以用来复制文件,如下:

>>> import shutil
>>> shutil.copy('/Users/xxx/test_file.txt','/Users/xxx/test_file_copy.txt')
'/Users/xxx/test_file_copy.txt'
>>>
>>> shutil.move('/Users/xxx/test_file_copy.txt','/Users/xxx/test_file_copy2.txt')
'/Users/xxx/test_file_copy2.txt'
>>>

remove()相比copy(),会把原文件删除。

5 重命名文件

使用os模块中的rename()函数可以用来重命名一个文件,如下:

>>> import os
>>> os.rename('/Users/xxx/test_file_copy2.txt','/Users/xxx/test_file_will_be_delete.txt')
>>>

6 删除文件

使用os模块中的remove()函数可以删除一个文件,如下:

>>> os.remove('/Users/liuchun/test_file_will_be_delete.txt')
>>>

7 创建link

os模块中的link()函数可以用来创建文件的硬链接,symlink()函数可以用来创建软链接,如下:

>>> import os
>>> os.link('/Users//test_file.txt','/Users/xxx/test_file_hardlink')
>>> os.symlink('/Users/xxx/test_file.txt','/Users/xxx/test_file_softlink')
>>> xxxdembp:~ xxx$ ls -l test_file*
-rw-r--r-- 2 xxx staff 46 11 14 18:09 test_file.txt
-rw-r--r-- 2 xxx staff 46 11 14 18:09 test_file_hardlink
lrwxr-xr-x 1 xxx staff 28 11 14 18:36 test_file_softlink -> /Users/xxx/test_file.txt

有关硬链接和软链接的知识请自行科普。

8 修改权限/所有者

os模块中的chmod()用来修改文件权限,这个命令接收一个压缩过的八进制(基数为 8)值,这个值包含用户、用户组和权限。而chown()用来修改文件的所有者,如下:

xxxdembp:~ xxx$ ls -l test_file.txt
-rw-r--r-- 2 xxx staff 46 11 14 18:09 test_file.txt >>> os.chmod('/Users/xxx/test_file.txt',0o777) xxxdembp:~ xxx$ ls -l test_file.txt
-rwxrwxrwx 2 xxx staff 46 11 14 18:09 test_file.txt
xxxdembp:~ xxx$
>>> uid = 5
>>> gid = 22
>>> os.chown('/Users/xxx/test_file.txt', uid, gid)

9 获取路径

使用os模块中的abspath()可以获取文件的绝对路径,使用realpath()可以获取软链接对应的路径。

>>> os.path.abspath('/Users/xxx/test_file.txt')
'/Users/xxx/test_file.txt'
>>> os.path.realpath('/Users/xxx/test_file_hardlink')
'/Users/xxx/test_file_hardlink'
>>> os.path.realpath('/Users/xxx/test_file_softlink')
'/Users/xxx/test_file.txt'
>>>

目录操作

os模块中的一些函数也可以对操作系统中的目录进行操作。

1 创建目录

使用os模块中的mkdir()可以创建目录,如下:

>>> import os
>>> os.mkdir('/Users/xxx/test_dir')
>>> os.path.exists('/Users/xxx/test_dir')
True
>>>

2 列出目录内容

使用os模块的listdir()可以列出目录中的内容,如下:

test_dir目录为空
>>> os.listdir('/Users/liuchun/test_dir')
[] 在test_dir中创建一个子目录2nd_layer_dir和一个文件test_file1
>>> os.listdir('/Users/liuchun/test_dir')
['2nd_layer_dir', 'test_file1']
>>>

3 切换工作目录

使用os模块中的chdir()可以切换当前的工作目录,如下:

>>> os.listdir('/Users/xxx/test_dir')
['2nd_layer_dir', 'test_file1']
>>> os.chdir('/Users/xxx/')
>>> os.listdir('.')
['.anyconnect', '.bash_history', '.bash_profile', '.bash_sessions', '.CFUserTextEncoding', '.cisco', 'test_dir', 'test_file.txt', 'test_file_hardlink', 'test_file_softlink', 'VirtualBox VMs']
>>>

4 删除目录

使用os模块中的rmdir()函数可以删除目录,如下:

>>> os.rmdir('/Users/xxx/test_dir')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: [Errno 66] Directory not empty: '/Users/xxx/test_dir' # 目录不为空的时候删除会报如上错误,清空后可以删除如下
>>> os.rmdir('/Users/xxx/test_dir')
>>>

5 查找匹配的文件目录

使用glob模块的glob()函数可以用来查找匹配文件或者目录,匹配的规则如下:

• *  匹配任意名称
• ?  匹配一个字符
• [abc]  匹配字符 a、b 和 c
• [!abc] 匹配除了 a、b 和 c 之外的所有字符

几个例子如下:

>>> import glob
>>> glob.glob('/Users/xxx/test*')
['/Users/xxx/test_dir', '/Users/xxx/test_file.txt', '/Users/xxx/test_file_hardlink', '/Users/xxx/test_file_softlink']
>>>
# 匹配以test开头的文件和目录 # 匹配以M或者D开头,s结尾的文件或目录
>>> glob.glob('/Users/xxx/[MD]*s')
['/Users/xxx/Documents', '/Users/xxx/Downloads', '/Users/xxx/Movies', '/Users/xxx/MyDocuments']
>>>

程序/进程操作

1 一些基础操作

os模块中的函数可以获取进程号,当前工作目录,用户id和组id,如下:

>>> import os
>>> os.getpid() #获取python解释器的pid
5541
>>> os.getcwd() #获取当前工作目录
'/Users/xxx'
>>> os.getuid() #获取 user id
501
>>> os.getgid() # 获取 group id
20
>>>

2 启动/执行进程

2.1 使用subprocess

使用subprocess模块可以执行命令,这个会生成一个子进程去执行。

getoutput()函数

返回命令执行结果

>>> import subprocess
>>> ret = subprocess.getoutput('date')
>>> ret
'2016年11月14日 星期一 22时14分39秒 CST'
>>>

getstatusoutput()函数

返回状态码和命令执行结果

>>> ret = subprocess.getstatusoutput('date')
>>> ret
(0, '2016年11月14日 星期一 22时18分04秒 CST')
>>> ret2 = subprocess.getstatusoutput('ll')
>>> ret2
(127, '/bin/sh: ll: command not found')
>>>

call()函数

获取命令执行状态

>>> ret3 = subprocess.call('ls -l',shell=True)
total 80
drwx------+ 8 xxx staff 272 11 14 14:34 Desktop
drwx------+ 8 xxx staff 272 11 3 15:21 Documents
drwx------+ 23 xxx staff 782 11 14 18:04 Downloads
drwxr-xr-x 3 xxx staff 102 11 3 16:07 IBMERS
drwx------@ 57 xxx staff 1938 11 14 12:45 Library
drwx------+ 3 xxx staff 102 11 3 11:09 Movies
drwx------+ 4 xxx staff 136 11 4 18:36 Music

2.2 使用multiprocessing创建执行多个进程

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() 192:python$ python3 mp.py
Process 9088 says: I'm the main program
Process 9089 says: I'm function 0
Process 9090 says: I'm function 1
Process 9091 says: I'm function 2
Process 9092 says: I'm function 3

时间和日期操作

python中提供了多种模块用于时间和日期的操作,比如calendar,datetime,time等模块。

1 datetime模块

定义了4个主要的对象,每个对象有各自的方法:

• date 处理年、月、日
• time 处理时、分、秒和分数
• datetime 处理日期和时间同时出现的情况
• timedelta 处理日期和 / 或时间间隔

 >>> from datetime import date
>>> halloween = date(2014, 10, 31)
>>> halloween
datetime.date(2014, 10, 31)
>>> halloween.day
31
>>> halloween.month
10
>>> halloween.year
2014 >>> halloween.isoformat()
'2014-10-31'
>>> >>> now=date.today()
>>> now
datetime.date(2016, 11, 14)
>>> >>> from datetime import timedelta
>>> one_day = timedelta(days=1)
>>> tomorrow = now + one_day
>>> tomorrow
datetime.date(2016, 11, 15)
>>> now + 17*one_day
datetime.date(2016, 12, 1)
>>> yesterday = now - one_day
>>> yesterday
datetime.date(2016, 11, 13)
>>> #datetime 模块中的 time 对象用来表示一天中的时间
>>> from datetime import time
>>> noon = time(12,0,0)
>>> noon
datetime.time(12, 0)
>>> noon.hour
12
>>> noon.minute
0
>>> noon.second
0
>>> noon.microsecond
0
>>> >>> from datetime import datetime
>>> some_day = datetime(2016, 11, 12, 13, 24, 35,56)
>>> some_day.isoformat()
'2016-11-12T13:24:35.000056'
>>> >>> now = datetime.now()
>>> now
datetime.datetime(2016, 11, 14, 23, 46, 4, 459142)
>>>

example

2 time模块

 #time 模块的 time() 函数会返回当前时间的纪元值,距离1970年1月1日0点开始的秒数
>>> import time
>>> now = time.time()
>>> now
1479138472.081136
>>> >>> time.ctime(now)
'Mon Nov 14 23:47:52 2016'
>>> #struct_time对象,ocaltime() 会 返回当前系统时区下的时间,gmtime() 会返回 UTC 时间
>>> time.localtime(now)
time.struct_time(tm_year=2016, tm_mon=11, tm_mday=14, tm_hour=23, tm_min=47, tm_sec=52, tm_wday=0, tm_yday=319, tm_isdst=0)
>>> time.gmtime(now)
time.struct_time(tm_year=2016, tm_mon=11, tm_mday=14, tm_hour=15, tm_min=47, tm_sec=52, tm_wday=0, tm_yday=319, tm_isdst=0)
>>> # 转换为纪元值
>>> tm = time.localtime(now)
>>> time.mktime(tm)
1479138472.0
>>> #strftime()把时间和日期转换成字符串
>>> import time
>>> fmt = "It's %A, %B %d, %Y, local time %I:%M:%S%p"
>>> t = time.localtime()
>>> t
time.struct_time(tm_year=2014, tm_mon=2, tm_mday=4, tm_hour=19,
tm_min=28, tm_sec=38, tm_wday=1, tm_yday=35, tm_isdst=0)
>>> time.strftime(fmt, t)
"It's Tuesday, February 04, 2014, local time 07:28:38PM" #strptime()把字符串转换成时间和日期
>>> time.strptime("2012-01-29", fmt)
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) #针对不同的语言地区输出不同的日期
>>> 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',]:
... locale.setlocale(locale.LC_TIME, lang_country)
... halloween.strftime('%A, %B %d') ...
'en_us'
'Friday, October 31'
'fr_fr'
'Vendredi, octobre 31'
'de_de'
'Freitag, Oktober 31'
'es_es'
'viernes, octubre 31'
'is_is'
'föstudagur, október 31'
>>> #lang_country的值可以这样获取
>>> import locale
>>> names = locale.locale_alias.keys()

example

Python系统(os)相关操作的更多相关文章

  1. Python字符串的相关操作

    1.大小写转换 判断字符串 s.isalnum() #所有字符都是数字或者字母 s.isalpha() #所有字符都是字母 s.isdigit() #所有字符都是数字 s.islower() #所有字 ...

  2. python文件的相关操作

    python 目录 python 1.python文件的介绍 使用文件的目的 Python文件的类型主要有两种:文本文件和二进制文件. 操作文件的流程主要有三步:打开-操作-关闭操作. 2.文件的打开 ...

  3. Selenium2+python自动化40-cookie相关操作

    前言 虽然cookie相关操作在平常ui自动化中用得少,偶尔也会用到,比如登录有图形验证码,可以通过绕过验证码方式,添加cookie方法登录. 登录后换账号登录时候,也可作为后置条件去删除cookie ...

  4. python中OS模块操作文件和目录

    在python中执行和操作目录和文件的操作是通过内置的python OS模块封装的函数实现的. 首先导入模块,并查看操作系统的类型: >>> import os os.name # ...

  5. Selenium2+python自动化40-cookie相关操作【转载】

    前言 虽然cookie相关操作在平常ui自动化中用得少,偶尔也会用到,比如登录有图形验证码,可以通过绕过验证码方式,添加cookie方法登录. 登录后换账号登录时候,也可作为后置条件去删除cookie ...

  6. Linux系统防火墙相关操作

    服务器重启后防火墙会自动开启,需要把防火墙关闭 以下为对防火墙进行的相关操作 查看防火墙状态 systemctl status firewalld service iptables status 暂时 ...

  7. python os相关操作

    python os模块常用操作 什么时候使用os模块? 操作文件及文件夹(对于文件及文件夹的增删改查) 1.获取当前文件夹的工作目录 注意不是当前文件所在文件,即当前执行python文件的文件夹 pr ...

  8. Python字典及相关操作(内含例题)

    Python字典类型 今天将会介绍一种在python中十分常见的组合数据类型——字典 通过一些实例来理解字典中的常规操作 什么是字典类型? 列表中查找是通过整数的索引(元素在列表中的序号)来实现查找功 ...

  9. python之线程相关操作

    1.线程: 一个进程可以有多个线程,共享一个进程的资源: 2.进程线程的区别:  进程是资源分配的最小单位,线程是程序执行的最小单位 3.python中线程模块threading, 提供的类: Thr ...

随机推荐

  1. ThinkPHP框架数组定义

    PHP数组定义 ThinkPHP框架中所有配置文件的定义格式均采用返回PHP数组的方式,格式为: //项目配置文件 return array( 'DEFAULT_MODULE' => 'Inde ...

  2. 53 windows 系统下

    0 引言 本篇主要记录windows下编程以及系统安装与恢复等问题. 1 Visual Studio (1)debug "warning LNK4042: 对象被多次指定:已忽略多余的指定& ...

  3. k8s 存储 nfs服务

    1.所有节点安装nfs yum install nfs-utils -y 2.配置nfs服务端,在master节点上 vim exports /data 10.0.0.0/24(rw,async,no ...

  4. Python匹马行天下之_循环

    一.while循环 如果条件成立(true),重复执行相同操作,条件不符合,跳出循环 while   循环条件: 循环操作 (1)while循环示例 例:输入王晓明5门课程的考试成绩,计算平均成绩 1 ...

  5. 24-Ubuntu-文件和目录命令-查找文件内容-grep

    grep Linux系统中grep命令是一种强大的文本搜索工具. grep允许文本文件进行模式查找,所谓模式查找,又被称为正则表达式. 选项 含义 -n 显示匹配行及行号 -v 显示不包括匹配文本的所 ...

  6. docker集群管理之swarm

    一.简介 docker集群管理工具有swarm.k8s.mesos等,我所用到的是swarm和k8s,这篇文章主要介绍swarm:swarm是docker集成的原生 管理工具,只要你安装上docker ...

  7. Mysql优化-字段设计

    摘抄并用于自查笔记 1. 对精度有要求decimal float 类型用于表示单精度浮点数值,而double类型用于表示双精度浮点数值,float 和 double 都是浮点型,而 decimal 是 ...

  8. 服务启动脚本start_boot.sh

    vim start_boot.sh #!/bin/bash usage(){ echo "$0 [start|stop|usage]" } status_springboot(){ ...

  9. C#学习笔记----反射基础

    反射基础 反射用于在程序运行过程中,获取类里面的信息或发现程序集并运行的一个过程.通过反射可以获得.dll和.exe后缀的程序集里面的信息.使用反射可以看到一个程序集内部的类,接口,字段,属性,方法, ...

  10. Java迷宫代码,广度优先遍历,最短路径

    使用一个队列,采用层层扩张的方式,寻找迷宫最优的路径信息,再用一个迷宫节点数组记录行走信息方向常量定义: public interface Constant { // 右方向 int RIGHT = ...