Python进阶篇-目录与文件(命名管理)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_39591494/article/details/82814927

Python进阶篇-目录与文件的(命名管理)


1、命名管理(路径的各级名称)

  • path.split(os.path.sep)
  • os.path.basename()
  • os.path.dirname()

2、删除文件

  • os.unlink
  • shutil.rmtree(path)

3、复制和移动 shutil

  • copy
  • copytree
  • move
import os
test_path = (r"F:\python_test1\Yankerp_test\result_test")
os.path.sep
>>>'\\'
test_path.split(os.path.sep)
>>>['F:', 'python_test1', 'Yankerp_test', 'result_test']

os.path.split

os.path.split(test_path)
>>>('F:\\python_test1\\Yankerp_test', 'result_test')

os.path.splitext

os.path.splitext(test_path)
>>>('F:\\python_test1\\Yankerp_test\\result_test', '')

os.path.splitext(r"F:\python_test1\Yankerp_test\result_test\1.docx")
>>>('F:\\python_test1\\Yankerp_test\\result_test\\1', '.docx')

os.path.split(r"F:\python_test1\Yankerp_test\result_test\1.docx")
>>>('F:\\python_test1\\Yankerp_test\\result_test', '1.docx')

os.path.basename() && os.path.dirname()

test_path = (r"F:\python_test1\Yankerp_test\result_test")

os.path.basename(test_path)
>>>result_test

os.path.dirname(test_path)
>>>'F:\\python_test1\\Yankerp_test'

二、删除文件或目录


2.1、删除一个目录

import shutil
shutil.rmtree("zhangsan") # zhangsan为目录名

2.2、删除文件(1.docx)

os.getcwd()
>>>'F:\\python_test1\\Yankerp_test\\result_test'

os.listdir()
['1.docx',
 '1.jfif',
 '2-1G22QK950918.jpg',
 '2.pptx',
 '21.png',
 '2DEngineDll.dll',
 '3.png',
 '31.jpg',
 '4.jpg',
 'bugreport.exe',
 'CardRes.dll',
 'COMToolKit.dll',
 'config.ini',
 'CUQG.ocx',
 'dbghelp.dll',
 'Factory.dll',
 'Factory2.dll',
 'GameListMenu1.dll',
 'GamePublic.dll',
 'GdiPlus.dll',
 'hcq.dll',
 'HelpDll.dll',
 'ImageOle.dll',
 'ItemDisp.dll',
 'navicatformysql.zip',
 'robomongo-1.0.0-windows-x86_64-89f24ea.rar',
 'securcrt.pc141.com.rar',
 'tt.sh',
 'zhangsan',
 'zhangsan_test.pptx',
 '啊.png',
 '新建 WinRAR 压缩文件.rar']
os.unlink("1.docx") # 删除1.docx文件

2.3、复制,移动(21.png)

import shutil
shutil.copy("21.png","2121.png")
os.listdir()
['1.jfif',
 '2-1G22QK950918.jpg',
 '2.pptx',
 '21.png',
 '2121.png',
 '2DEngineDll.dll',]

2.4、移动

shutil.move("3.png","3131.png")

猜你喜欢

转载自blog.csdn.net/qq_39591494/article/details/82814927