OS模块

2017-07-19  本文已影响0人  merryzhou

记录常用命令:

>>> os.name
'posix'         #unix/Linux,返回posix;windows用户,返回nt
>>> os.sep
'/'              #unix/linux
>>> os.sep
'\\'             #windows
>>> os.linesep
'\n'            #linux
>>> os.linesep
'\r\n'        #windows
>>> os.environ
{..., 'PWD': '/Users/merry'}
>>> os.getcwd()
'/Users/merry'
>>> os.mkdir('tmp1/tmp2')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 2] No such file or directory: 'tmp1/tmp2'
>>> 
>>> os.mkdir('tmp1')
>>> os.makedirs('tmp/tmp_file')
>>> os.listdir('tmp')
['tmp_file']
>>> os.chdir('tmp')
>>> os.curdir
'.'
>>> os.getcwd()
'/Users/merry/tmp'
>>> os.listdir('.')
['tmp_file']
>>> os.rename('tmp_file','new')
>>> os.listdir('.')
['new']
>>> os.makedirs('new/a/b')
>>> os.rmdir('new')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 66] Directory not empty: 'new'
>>> os.removedirs('new')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 170, in removedirs
    rmdir(name)
OSError: [Errno 66] Directory not empty: 'new'
>>> os.rmdir('new/a/b')
>>> os.listdir('./new')
['a']
>>> os.listdir('./new/a')
[]
>>> os.removedirs('new/a')
>>> os.listdir('.')
[]
>>> open('file','w')
<open file 'file', mode 'w' at 0x1083c35d0>
>>> open('file.txt','w')
<open file 'file.txt', mode 'w' at 0x1083c3660>
>>> os.listdir('.')
['file', 'file.txt']
>>> os.remove('file')
>>> os.listdir('.')
['file.txt']
>>> os.path.abspath('a/b')
'/Users/merry/tmp/a/b'
>>> os.path.abspath('/a/b')
'/a/b'
>>> os.path.dirname('/a/b')
'/a'
>>> os.path.dirname('a/b')
'a'
>>> os.path.dirname('a/b/')
'a/b'
>>> os.path.basename('a/b/')
''
>>> os.path.basename('a/b')
'b'
>>> os.path.isfile('file.txt')
True
>>> os.path.isdir('file.txt')
False
>>> os.stat('file.txt')
posix.stat_result(st_mode=33188, st_ino=3287829, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=0, st_atime=1500473283, st_mtime=1500473273, st_ctime=1500473273)
>>> os.chmod('file.txt', 0777)
>>> os.stat('file.txt')
posix.stat_result(st_mode=33279, st_ino=3287829, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=0, st_atime=1500473283, st_mtime=1500473273, st_ctime=1500473741)
>>> 
>>> os.path.split('a/b/c')
('a/b', 'c')
>>> os.path.split('a/b/c/')
('a/b/c', '')
>>> os.path.split('/a/b/c/')
('/a/b/c', '')
>>> os.path.join('a/b','c')
'a/b/c'
>>> os.path.exists('a/b/c')
False
上一篇下一篇

猜你喜欢

热点阅读