首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python3基础:目录操作

python3基础:目录操作

作者头像
py3study
发布2020-01-09 23:53:42
1.2K0
发布2020-01-09 23:53:42
举报
文章被收录于专栏:python3python3

目录操作

os模块提供了统一的操作系统接口函数,python中对文件和文件夹的操作都要涉及到os和shutil模块,在使用前需要使用import引入,例如;

import os

import os.path

import shutil

os.getcwd()

获取当前工作目录,即当前Python脚本工作的目录路径

>>> import os

>>> os.getcwd()

'F:\\'

os. chdir(path)

改变当前脚本工作目录,相当于linux下的cd命令

>>> os.getcwd()

'F:\\py3.6\\PPT'

>>> os.chdir('f:')#错误的写法,不会切换路径

>>> os.getcwd()

'F:\\py3.6\\PPT'

>>> os.chdir('f:\\')#盘符后面必须写上\\

>>> os.getcwd()

'F:\\'

>>> os.chdir('f:\\py3.6')#绝对路径

>>> os.getcwd()

'f:\\py3.6'

>>> os.chdir('test')#相对路径

>>> os.getcwd()

'f:\\test'

>>>

os.curdir

获取当前路径,也就是('.')

>>> os.curdir

'.'

​​​​​​​os.pardir

 返回当前目录的父目录('..')

>>> os.pardir

'..'

>>> os.chdir(os.pardir)

>>> os.getcwd()

'f:\\'

​​​​​​​os.name

获取当前使用的操作系统类型(其中 ‘nt’ 是 windows,’posix’ 是

linux 或者 unix)。

>>> os.name

'nt'

​​​​​​​os.mkdir(path [, mode=0777])

创建单级目录

>>> os.getcwd()

'f:\\'

>>> os.mkdir('20181014')

>>> os.mkdir('20181014')#再次创建抛异常

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

FileExistsError: [WinError 183] 当文件已存在时,无法创建该文件。: '20181014'

>>>

​​​​​​​s.makedirs(path [, mode=0777])

创建多级目录,父目录如果不存在,递归生成。生成的目录权限默认为777.如果重复创建会出错

>>> os.getcwd()

'f:\\'

>>> os.makedirs('11\\22\\33')

>>> os.makedirs('11\\22\\33')

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

  File "C:\Users\kongsh\AppData\Local\Programs\Python\Python36\lib\os.py", line220, in makedirs

    mkdir(name, mode)

FileExistsError: [WinError 183] 当文件已存在时,无法创建该文件。: '11\\22\\33'

​​​​​​​os.removedirs(path)

删除多级目录,目录为空才能删除,递归到上一级为空才能删除,不为空的话没有任何影响

os.removedirs('11\\22\\33')

​​​​​​​os.rmdir(path)

删除单级目录,不为空无法删除,会报错

​​​​​​​os.listdir(path)

列出指定目录下的所有文件和子目录,包括隐藏文件或目录,并以列表形式返回。path不写的话默认为当前目录

>>> os.listdir('.')

['$RECYCLE.BIN','20181014' 'a.py', 'AutoTestLog.log', 'b.txt', 'bip32.txt', 'PBKDF.txt', '

pet-shop-tutorial', 'System Volume Information', 'upload_file.exe', '区块链']

>>>

>>> os.listdir()#默认为当前python脚本目录

['$RECYCLE.BIN','20181014' 'a.py', 'AutoTestLog.log', 'b.txt', 'bip32.txt', 'PBKDF.txt', '

pet-shop-tutorial', 'System Volume Information', 'upload_file.exe', '区块链']

>>> os.listdir('F:\\20181014')

['11', 'Log.py']

​​​​​​​os.remove(filePath)

删除指定文件,并且只能删除文件

>>> os.chdir(r'F:\20181014')

>>> os.getcwd()

'F:\\20181014'

>>> os.listdir()

['11', 'a.txt', 'Log.py']

>>> os.remove('a.txt')

>>> os.listdir()

['11', 'Log.py']

>>> os.remove('11')#删除目录会抛出PermissionError异常

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

PermissionError: [WinError 5] 拒绝访问。: '11'

​​​​​​​os.rename(oldname, newname)

重命名文件/目录

>>> os.rename('b.txt','bbb.txt')

>>> os.listdir()

['$RECYCLE.BIN', '20181014', 'a.py', 'AutoTestLog.log', 'bbb.txt', 'bip32.txt',

'PBKDF.txt', 'pet-shop-tutorial', 'System Volume Information', 'upload_file.exe'

, '区块链']

​​​​​​​os.stat(path)

获取文件信息,比如文件大小/创建时间/修改时间等等

>>> os.stat('bbb.txt')

os.stat_result(st_mode=33206, st_ino=1407374883603027, st_dev=2862993929, st

nk=1, st_uid=0, st_gid=0, st_size=9, st_atime=1539497709, st_mtime=153949770

t_ctime=1532852412)

>>> os.stat('bbb.txt').st_mtime #用.来取对应的键

1539497709.5655668

​​​​​​​os.utime(path[, (atime, mtime)])

修改文件的时间属性,设置文件的access and modified time

>>> os.stat('bbb.txt')

os.stat_result(st_mode=33206, st_ino=1407374883603027, st_dev=2862993929, st

nk=1, st_uid=0, st_gid=0, st_size=9, st_atime=1539497709, st_mtime=153949770

t_ctime=1532852412)

>>> os.utime(r'bbb.txt',(1375448978,1369735977))

>>> os.stat('bbb.txt')

os.stat_result(st_mode=33206, st_ino=1407374883603027, st_dev=2862993929, st

nk=1, st_uid=0, st_gid=0, st_size=9, st_atime=1375448978, st_mtime=136973597

t_ctime=1532852412)

>>> import os .path >>> os.path.isdir("subprocesstest") True >>> os.path.isfile("subprocesstest") False

​​​​​​​os.system (command)

运行shell命令

window下:

>>> os.system('dir')

linux下:

>>> import os

>>> os.system('ls')

​​​​​​​os.sep

输出操作系统的特定的路径分隔符。 Win下为“\”,Linux下为“/”

>>> os.sep

'\\'

​​​​​​​os.linesep

输出当前平台使用的行终止符,win 下为“\r\n”,Linux下为“\n”,Mac使用 '\r'。

>>> os.linesep#linux默认是'\n'

'\r\n'​​​​​​​

os.pathsep

输出用于分割文件路径的字符串。

>>> os.pathsep

';'​​​​​​​

os.environ()

获取系统环境变量,返回的是字典

>>> os.environ['os']#通过指定键的方式查看对应的值

'Windows_NT'

​​​​​​​os.poen()

运行一个shell命令打开一个管道,并且返回一个文件对象。然后通过操作文件的方式去操作这个返回值即可

语法:os.popen(command[, mode[, bufsize]])

参数:

command -- 使用的命令。

mode -- 模式权限可以是 'r'(默认) 或 'w'。

bufsize -- 指明了文件需要的缓冲大小:0意味着无缓冲;1意味着行缓冲;其它正值表示使用参数大小的缓冲(大概值,以字节为单位)。负的bufsize意味着使用系统的默认值,一般来说,对于tty设备,它是行缓冲;对于其它文件,它是全缓冲。如果没有改参数,使用系统的默认值。

返回值:

返回一个文件描述符号为fd的打开的文件对象

windows:

>>> for i in os.popen('dir'):

...     print(i)

...

linnux:

>>> import os

>>> for i in os.popen('ls'):

...     print(i)

...

a.py

b.py

​​​​​​​os.walk(top, topdown=True, οnerrοr=None, followlinks=False)

参数说明:

➢top:需要遍历的目录树的路径。

➢topdown的默认值是“True”,表示先返回目录树下的文件,然后遍历目录树下的子目录。设为False时,表示先遍历目录树下的子目录,返回子目录下的文件,最后返回根目录下的文件。

➢onerror的默认值是“None”,表示忽略文件遍历时产生的错误。如果不为空,则提供一个自定义函数提示错误信息后继续遍历或抛出异常中止遍历。

➢返回一个列表,列表中的每一个元素都是一个元组,该元组有3个元素,分别表示每次遍历的路径名目录列表文件列表

➢默认情况下os.walk 不会遍历软链接指向的子目录,若有需要请将followlinks设定为true(软连接:类似与window的快捷方式)

代码示例:遍历指定文件夹下所有的文件和目录

#encoding=utf-8 import os dir_count=0 file_count=0 for root, dirs, files in os.walk("e:\\testdemo",topdown=False) :     print(u"当前目录:",root) #打印目录绝对路径     for name in files :         print(u'文件名:',os.path.join(root,name) )#打印文件绝对路径         file_count+=1     for name in dirs :         print(u'目录名:',name) #打印目录绝对路径         dir_count+=1 print ("目录个数%s" %dir_count) print ("文件个数%s" %file_count)

​​​​​​​os.path.abspath(path)

返回规范化的绝对路径名,根据当前工作目录路径连接该文件名后所组成的新的路径名,但这个路径不一定是真实存在的路径

>>> os.path.abspath('a.txt')

'f:\\a.txt'

​​​​​​​os.path.join((a, *p)

连接两个或更多的路径名拼接成绝对路径,中间以“\”分隔,如果所给的参数中都是绝对路径名,那先给的绝对路径将会被丢弃。

>>> import os.path >>> os.path.join("e:\\test","a.txt") 'e:\\test\\a.txt' >>> os.path.join("test","a.txt") 'test\\a.txt' >>> os.path.join("e:\\test","e:\\a.txt") 'e:\\a.txt' >>> os.path.join(r"e:\test",r"e:\a.txt") 'e:\\a.txt'

​​​​​​​os.path.split(path)

将path分割成目录和文件名,如果给的path本身就是目录的话,也会将最后一个目录作为文件名而分离,同时它不会判断文件或目录是否存在,以元组返回

>>> os.path.split('f:\\a.txt')

('f:\\', 'a.txt')

>>> os.path.split('f:\\test\\a.txt')

('f:\\test', 'a.txt')

>>> os.path.split('f:\\test')#将目录作为文件名分割

('f:\\', 'test')

​​​​​​​os.path.dirname(path)

返回path的目录路径,就是os.path.split(path)的第一个元素。

>>> os.path.dirname('f:\\test\\a.txt')

'f:\\test'

​​​​​​​os.path.basename(path)

返回path最后的文件名。如果path以/或\结尾,就会返回空值。即os.path.split(path)的第二个元素

>>> os.path.basename('f:\\test\\a.txt')

'a.txt'

​​​​​​​os.path.splitext(path)

分离文件名与扩展名

>>> os.path.splitext('f:\\test\\a.txt')

('f:\\test\\a', '.txt')

​​​​​​​os.path.splitdrive(path)

拆分驱动器和文件路径,并以元组返回结果;主要针对win有效,Linux元组第一个总是空。

>>> os.path.splitdrive('c:\\a.py')

('c:', '\\a.py')

>>> os.path.splitdrive('a.py')

('', 'a.py')

>>>

​​​​​​​os.path.exists(path)

判断path是否存在,如果存在返回True,否则返回False。比如新建文件的时候可以使用

>>> os.path.exists('c:\\a.py')

False

>>> os.path.exists('f:\\a.py')

True

​​​​​​​os.path.isabs(path)

判断path是否是绝对路径,如果是返回True,否则返回False。

>>> os.path.isabs('c:\\aaaaaaaaaa.txt')

True

>>> os.path.isabs('aaaaaaaaaa.txt')

False

​​​​​​​os.path.isfile(path)

判断path是否是文件,如果是返回True,否则返回False。必须是真实存在的文件

>>> os.path.isfile(r'd:\gloryroad\a.py')

False

>>> os.path.isfile(r'f:\\a.py')

True

​​​​​​​os.path.isdir(path)

判断path是否是目录,如果是目录返回True,否则返回False。必须是真实存在的目录

>>> os.path.isdir(r"F:\20181014\11")

True

>>> os.path.isdir(r"F:\20181014\22")#目录不存在

False

>>> os.path.isdir(r"F:\20181014\Log.py")#指定的是文件

False

​​​​​​​os.path.normpath(path)

将path转换成规范的文件路径

>>> os.path.normpath('c:/test/a.py')

'c:\\test\\a.py'

​​​​​​​os.path.getsize(name)

获得文件大小,如果name是目录返回结果是0L或者4096L;如果name代表的目录或文件不存在,会报WindowsError异常。

>>> os.path.getsize(r'f:\\a.py')

44

>>> os.path.getsize(r'f:')

4096

​​​​​​​os.path.getatime(filename)

返回文件的最后访问时间,返回的是时间戳。

import os

import time

#获取文件最后访问时间

lastTime = os.path.getatime("test12.py")

print(lastTime)

#将时间戳转成时间元组

formatTime = time.localtime(lastTime)

print(formatTime)

#格式化时间元组为时间字符串

print(time.strftime("%Y-%m-%d %H:%M:%S",formatTime))

​​​​​​​os.path.getctime(filename)

以时间戳的形式返回文件或目录的创建时间,在Unix系统上是文件最近更改的时间,在Windows上是文件或目录的创建时间。

import os

import time

#获取文件创建时间

lastTime = os.path.getctime("test12.py")

print(lastTime)

#将时间戳转成时间元组

formatTime = time.localtime(lastTime)

print(formatTime)

#格式化时间元组为时间字符串

print(time.strftime("%Y-%m-%d %H:%M:%S",formatTime))

​​​​​​​os.path.getmtime(filename)

以时间戳的形式返回文件或目录的最后存取时间

import os

import time

#获取文件创建时间

lastTime = os.path.getmtime("test12.py")

print(lastTime)

#将时间戳转成时间元组

formatTime = time.localtime(lastTime)

print(formatTime)

#格式化时间元组为时间字符串

print(time.strftime("%Y-%m-%d %H:%M:%S",formatTime))

​​​​​​​sys模块的命令行参数

sys.argv:交互模式下传入的命令行参数,第0个是文件名。将自己的程序发布给别人使用时,无需打开文件,直接从命令行参数输入数据,简单方便。

以下代码需在命令行下执行

代码示例1:对命令行输入的两个数字求和

#coding=utf-8

import os,time,sys

print(sys.argv)

def add(a,b):

      return a+b

if len(sys.argv)!=3:

      print('参数数量不对!')

      sys.exit()

try:

      float(sys.argv[1])

      float(sys.argv[2])

except:

      print('参数类型不对!请指定两个数字')

print(add(float(sys.argv[1]),float(sys.argv[2])))

代码示例2:对命令行输入的不同参数进行不同的处理

#coding=utf-8
import os,sys

def readfile(filename):
    '''Print a file to the standard output.'''
    f = open(filename)
    while True:
          line = f.readline()
          if len(line) == 0:
             break
          print (line,)
    f.close()
if len(sys.argv) ==2 and sys.argv[1].startswith('--'):
    pass
elif  len(sys.argv) <3:
   print ('No action specified.')
   sys.exit()

for id,i in enumerate(sys.argv):
    print ("第%s个参数:%s" %(id,i))

if sys.argv[1].startswith('--'):
    option = sys.argv[1][2:]
    # fetch sys.argv[1] but without the first two characters
    if option == 'version':
        print('Version 1.2')
    elif option == 'help':
        print('''"
           This program prints files to the standard output.
           Any number of files can be specified.
           Options include:
           --version : Prints the version number
           --help    : Display this help''')
    else:
        print('Unknown option.')
        sys.exit()
else:
    for filename in sys.argv[1:]:
        readfile(filename)

shutil模块

shutil模块可以方便的移动/复制/删除目录及文件。使用前需要导入import shutil

复制文件/文件夹

shutil.copyfile( src, dst) #src复制到dst中去。当然前提是目标地址是具备可写权限。抛出的异常信息为 IOException. 如果当前的dst已存在的话就会被覆盖掉 shutil.move( src, dst) #移动文件或重命名

shutil.copy( src, dst) 复制一个文件到一个文件或一个目录 shutil.copy("d:\\a.py","d:\\yy.py")

shutil.copy2( src, dst) #在copy上的基础上再复制文件最后访问时间与修改时间也复制过来了,类似于cp –p的东西

shutil.copytree( olddir, newdir, True/Flase)

#把olddir拷贝一份newdir,olddir和newdir都只能是目录,且newdir 必须不存在。如果第3个参数是True,则复制目录时将保持文件夹下的符号连接,如果第3个参数是False,则将在复制的目录下生成物理副本来替代符

移动文件(目录)

shutil.move("oldpos","newpos")   

shutil.move("d:\\aaa","d:\\ddd")

shutil.copytree( olddir, newdir, True/False) #把olddir拷贝一份newdir,如果第3个参数是True,则复制目录时将保持文件夹 下的符号连接,如果第3个参数是False,则将在复制的目录下生成物理副本来 替代符号连接

#shutil.rmtree( src ) 递归删除一个目录以及目录内的所有内容,并且删除后不能恢复

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-12 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 目录操作
  • os.getcwd()
  • os. chdir(path)
  • os.curdir
  • ​​​​​​​os.pardir
  • ​​​​​​​os.name
  • ​​​​​​​os.mkdir(path [, mode=0777])
  • ​​​​​​​s.makedirs(path [, mode=0777])
  • ​​​​​​​os.removedirs(path)
  • ​​​​​​​os.rmdir(path)
  • ​​​​​​​os.listdir(path)
  • ​​​​​​​os.remove(filePath)
  • ​​​​​​​os.rename(oldname, newname)
  • ​​​​​​​os.stat(path)
  • ​​​​​​​os.utime(path[, (atime, mtime)])
  • ​​​​​​​os.system (command)
  • ​​​​​​​os.sep
  • ​​​​​​​os.linesep
  • os.pathsep
  • os.environ()
  • ​​​​​​​os.poen()
  • ​​​​​​​os.walk(top, topdown=True, οnerrοr=None, followlinks=False)
  • ​​​​​​​os.path.abspath(path)
  • ​​​​​​​os.path.join((a, *p)
  • ​​​​​​​os.path.split(path)
  • ​​​​​​​os.path.dirname(path)
  • ​​​​​​​os.path.basename(path)
  • ​​​​​​​os.path.splitext(path)
  • ​​​​​​​os.path.splitdrive(path)
  • ​​​​​​​os.path.exists(path)
  • ​​​​​​​os.path.isabs(path)
  • ​​​​​​​os.path.isfile(path)
  • ​​​​​​​os.path.isdir(path)
  • ​​​​​​​os.path.normpath(path)
  • ​​​​​​​os.path.getsize(name)
  • ​​​​​​​os.path.getatime(filename)
  • ​​​​​​​os.path.getctime(filename)
  • ​​​​​​​os.path.getmtime(filename)
  • ​​​​​​​sys模块的命令行参数
  • shutil模块
    • 复制文件/文件夹
      • 移动文件(目录)
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档