Python 调用os执行类似linux/dos常见命令

本文通过示例展示了Python中os模块的各种文件和目录操作方法,包括文件删除、重命名、链接创建、权限修改等,并介绍了如何获取文件的元数据及进行路径处理。
# delete
>>> import os
>>> os.remove('2.txt')

# rename
>>> os.rename('1.txt', '2.txt')

# stat
>>> os.stat('2.txt')
posix.stat_result(st_mode=33204, st_ino=62806910, st_dev=2065L, st_nlink=1, st_uid=1002, st_gid=1002, st_size=0, st_atime=1421891918, st_mtime=1421891918, st_ctime=1421891931)

# symlink
>>> os.symlink('2.txt', '3.txt')
build@dev-18:~$ ls -l
total 48
-rw-rw-r--  1 build build     0 Jan 22 09:58 2.txt
lrwxrwxrwx  1 build build     5 Jan 22 09:59 3.txt -> 2.txt

# utime
>>> os.utime('2.txt', (1,1))
build@dev-18:~$ ls -l
total 48
-rw-rw-r--  1 build build     0 Jan  1  1970 2.txt
lrwxrwxrwx  1 build build     5 Jan 22 09:59 3.txt -> 2.txt
drwxrwxr-x 37 build build 45056 Jan 22 09:27 automation

# chdir
>>> os.chdir('/home/build')

# listdir
>>> os.listdir('/home/build')
['.profile', '.subversion', '.bash_logout', '3.txt', 'automation', '.jenkins', '.cache', '.bash_history', '.ssh', '.viminfo', '.tmp', '.bashrc', '.vim', '2.txt']

# getcwd
>>> os.getcwd()
'/home/build'

# mkdir
>>> os.mkdir('nihao')

# rmdir
>>> os.rmdir('nihao')

# chmod
>>> os.chmod('2.txt', 777)

# basename
>>> os.path.basename('/home/build/2.txt')
'2.txt'

# dirname
>>> os.path.dirname('/home/build/2.txt')
'/home/build'

# path join
>>> os.path.join('/home/build')
'/home/build'

# path split
>>> os.path.split('/home/build')
('/home', 'build')

# time
>>> os.path.getatime('2.txt')
1421892617.4191236
>>> os.path.getctime('2.txt')
1421893017.9684155
>>> os.path.getmtime('2.txt')
1421892617.4191236

# size
>>> os.path.getsize('2.txt')
19

# exist
>>> os.path.exists('2.txt')
True
>>> os.path.exists('3.txt')
True
>>> os.path.exists('4.txt')
False
>>> os.path.isabs('2.txt')
False
>>> os.path.isabs('/home/build/2.txt')
True
>>> os.path.isdir('/home/build/2.txt')
False
>>> os.path.isdir('/home/build')
True
>>> os.path.isfile('/home/build/2.txt')
True
>>> os.path.islink('/home/build/2.txt')
False
>>> os.path.islink('/home/build/3.txt')
True
>>> os.path.samefile('2.txt', '3.txt')
True

# expand
>>> os.path.expanduser('~/nihao')
'/home/build/nihao'

# any linux/dos cmd
>>> os.system('ls')
bug1107.tcl  bug1135.tcl  bug1675.tcl  bug1809.tcl  bug1871.tcl  bug1961.tcl  bug2833.tcl  bug3286.tcl  bug3398.tcl  bug520.tcl
bug1128.tcl  bug1551.tcl  bug1722.tcl  bug1829.tcl  bug1883.tcl  bug2261.tcl  bug2957.tcl  bug3344.tcl  bug415.tcl   tclIndex
0
>>> os.system('pwd')
/home/build/automation/suite/ovsBug
0
>>> 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值