python使用os和shutil模塊進行文件創建,刪除,移動,複製,重命名

python使用os和shutil模塊進行文件創建,刪除,移動,複製,重命名

文章目錄:


可以說在python對於文件和目錄的操作是經常性工作,那麼os和shutil這兩個模塊就是文件操作的左右手!!!

pathlib是一個比os.path更好用的庫包,參考


常用方法屬性如下:

os.sep    可以取代操作系統特定的路徑分隔符。windows下爲 '\\'
os.name    字符串指示你正在使用的平臺。比如對於Windows,它是'nt',而對於Linux/Unix用戶,它是 'posix'
os.getcwd()    函數得到當前工作目錄,即當前Python腳本工作的目錄路徑
os.getenv()    獲取一個環境變量,如果沒有返回none
os.putenv(key, value)    設置一個環境變量值
os.listdir(path)    返回指定目錄下的所有文件和目錄名
os.remove(path)    函數用來刪除一個文件
os.system(command)    函數用來運行shell命令
os.linesep    字符串給出當前平臺使用的行終止符。例如,Windows使用 '\r\n',Linux使用 '\n' 而Mac使用 '\r'
os.path.split(path)        函數返回一個路徑的目錄名和文件名
os.path.isfile()    和os.path.isdir()函數分別檢驗給出的路徑是一個文件還是目錄
os.path.exists()    函數用來檢驗給出的路徑是否真地存在
os.curdir        返回當前目錄 ('.')
os.mkdir(path)    創建一個目錄
os.makedirs(path)    遞歸的創建目錄
os.chdir(dirname)    改變工作目錄到dirname          
os.path.getsize(name)    獲得文件大小,如果name是目錄返回0L
os.path.abspath(name)    獲得絕對路徑
os.path.normpath(path)    規範path字符串形式
os.path.splitext()        分離文件名與擴展名
os.path.join(path,name)    連接目錄與文件名或目錄
os.path.basename(path)    返回文件名
os.path.dirname(path)    返回文件路徑
os.walk(top,topdown=True,οnerrοr=None)        遍歷迭代目錄
os.rename(src, dst)        重命名file或者directory src到dst 如果dst是一個存在的directory, 將拋出OSError. 在Unix, 如果dst在存且是一個file, 如果用戶有權限的話,它將被安靜的替換. 操作將會失敗在某些Unix 中如果src和dst在不同的文件系統中. 如果成功, 這命名操作將會是一個原子操作 (這是POSIX 需要). 在 Windows上, 如果dst已經存在, 將拋出OSError,即使它是一個文件. 在unix,Windows中有效。
os.renames(old, new)    遞歸重命名文件夾或者文件。像rename()



# shutil 模塊

shutil.copyfile( src, dst)    從源src複製到dst中去。當然前提是目標地址是具備可寫權限。拋出的異常信息爲IOException. 如果當前的dst已存在的話就會被覆蓋掉
shutil.move( src, dst)        移動文件或重命名
shutil.copymode( src, dst)    只是會複製其權限其他的東西是不會被複制的
shutil.copystat( src, dst)    複製權限、最後訪問時間、最後修改時間
shutil.copy( src, dst)        複製一個文件到一個文件或一個目錄
shutil.copy2( src, dst)        在copy上的基礎上再複製文件最後訪問時間與修改時間也複製過來了,類似於cp –p的東西
shutil.copy2( src, dst)        如果兩個位置的文件系統是一樣的話相當於是rename操作,只是改名;如果是不在相同的文件系統的話就是做move操作
shutil.copytree( olddir, newdir, True/Flase)
把olddir拷貝一份newdir,如果第3個參數是True,則複製目錄時將保持文件夾下的符號連接,如果第3個參數是False,則將在複製的目錄下生成物理副本來替代符號連接
shutil.rmtree( src )    遞歸刪除一個目錄以及目錄內的所有內容

1 os模塊的使用

OS模塊簡單的來說它是一個Python的系統編程的操作模塊,可以處理文件和目錄這些我們日常手動需要做的操作

在這裏插入圖片描述
這裏我們把os分成帶path和不帶path兩部分,這樣比較容易記憶

1.1 os不帶path

1.1.1 os.sep 屬性:返回系統路徑分隔符

os.sep: 是一個屬性,並沒有參數,是可以自動獲取系統路徑的分隔符(separation),並以字符串的形式返回

  • 沒有參數,是屬性
  • 返回系統的路徑分隔符
  • 返回類型字符串

Windows系統通過是“\”Linux類系統如Ubuntu的分隔符是“/”,而蘋果Mac OS系統中是“:”
使用os.sep代替系統分隔符可以實現跨平臺,不用擔心不能移植
Linux下一個路徑, ‘/usr/share/python’ 那麼上面的 os.sep 就是 ‘/’
Windows下一個路徑, ‘\usr\share\python’ 那麼上面的 os.sep 就是 ‘’。

舉例:

>>> os.sep
'\\'
>>> print(os.sep+"user"+os.sep+"test")
\user\test

1.1.2 os.name 屬性:返回使用平臺

os.name :輸出字符串指示正在使用的平臺。如果是window 則用’nt’表示,對於Linux/Unix用戶,它是’posix’。

  • 沒有參數,是屬性
  • 返回系統使用平臺
  • 返回類型是字符串

舉例:

>>> os.name
'nt'
>>> print(type(os.name))
<class

1.1.3 os.linesep 屬性:返回字符串行終止符

os.linesep: 字符串給出當前平臺使用的行終止符。例如,Windows使用 ‘\r\n’,Linux使用 ‘\n’ 而Mac使用 ‘\r’

  • 沒有參數,是屬性
  • 返回的是平臺的行終止符
  • 返回類型是字符串

舉例:

>>> os.linesep
'\r\n'
>>>

1.1.4 os.environ 屬性:返回系統所有的環境變量

os.environ :返回操作系統所有的環境變量

  • 沒有參數,是屬性
  • 返回的是系統種的所有變量
  • 返回類型是<class ‘os._Environ’>
    舉例:
>>> os.environ
environ({'ALLUSERSPROFILE': 'C:\\ProgramData', 'APPDATA': 'C:\\Users\\93176\\AppData\\Roaming', 'COMMONPROGRAMFILES': 'C:\\Program Files\\Common Files', 'COMMONPROGRAMFILES(X86)': 'C:\\Program Files (x86)\\Common Files', 'COMMONPROGRAMW6432': 'C:\\Program Files\\Common Files', 'COMPUTERNAME': 'SHLIANGPC', 'COMSPEC': 'C:\\WINDOWS\\system32\\cmd.exe', 'CONFIGSETROOT': 'C:\\WINDOWS\\ConfigSetRoot', 'CUDA_PATH': 'C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.0', 'CUDA_PATH_V10_0': 'C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.0', 'DRIVERDATA': 'C:\\Windows\\System32\\Drivers\\DriverData', 'FPS_BROWSER_APP_PROFILE_STRING': 'Internet Explorer', 'FPS_BROWSER_USER_PROFILE_STRING': 'Default', 'FREI0R_PATH': 'E:\\SOFTWA~1\\APOWER~1\\APOWER~1\\frei0r;E:\\software_install\\Apowershow_install\\ApowerShow\\frei0r', 'HOMEDRIVE': 'C:', 'HOMEPATH': '\\Users\\93176', 'INTEL_DEV_REDIST': 'C:\\Program Files (x86)\\Common Files\\Intel\\Shared Libraries\\', 'LOCALAPPDATA': 'C:\\Users\\93176\\AppData\\Local', 'LOGONSERVER': '\\\\SHLIANGPC', 'MIC_LD_LIBRARY_PATH': 'C:\\Program Files (x86)\\Common Files\\Intel\\Shared Libraries\\compiler\\lib\\intel64_win_mic', 'MOZ_PLUGIN_PATH': 'E:\\software_install\\FoxitReader_install\\Foxit Reader\\plugins\\', 'NUMBER_OF_PROCESSORS': '12', 'NVCUDASAMPLES10_0_ROOT': 'C:\\ProgramData\\NVIDIA Corporation\\CUDA Samples\\v10.0', 'NVCUDASAMPLES_ROOT': 'C:\\ProgramData\\NVIDIA Corporation\\CUDA Samples\\v10.0', 'NVTOOLSEXT_PATH': 'C:\\Program Files\\NVIDIA Corporation\\NvToolsExt\\', 'ONEDRIVE': 'C:\\Users\\93176\\OneDrive', 'ONEDRIVECONSUMER': 'C:\\Users\\93176\\OneDrive', 'OS': 'Windows_NT', 'PATH': 'C:\\ProgramData\\Anaconda3;C:\\ProgramData\\Anaconda3\\Library\\mingw-w64\\bin;C:\\ProgramData\\Anaconda3\\Library\\usr\\bin;C:\\ProgramData\\Anaconda3\\Library\\bin;C:\\ProgramData\\Anaconda3\\Scripts;C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.0\\bin;C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.0\\libnvvp;C:\\Program Files (x86)\\Common Files\\Intel\\Shared Libraries\\redist\\intel64_win\\compiler;C:\\windows\\system32;E:\\software_install\\ffmpeg\\bin;C:\\Program Files\\NVIDIA Corporation\\NVSMI;E:\\software_install\\frei0r-plugins-1.6.1;E:\\software_install\\PotPlayer_install\\PotPlayer\\PotPlayerMini64.exe;E:\\software_install\\MinGW_insatll\\bin;C:\\Program Files (x86)\\NVIDIA Corporation\\PhysX\\Common;C:\\Program Files\\NVIDIA Corporation\\NVIDIA NvDLISR;E:\\software_install\\Anaconda_install\\Lib;E:\\software_install\\Git_install\\bin;C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem;C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\;C:\\Program Files (x86)\\Graphviz2.38\\bin;C:\\Users\\93176\\AppData\\Local\\Microsoft\\WindowsApps;C:\\Users\\93176\\AppData\\Local\\GitHubDesktop\\bin;C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.0\\bin;C:\\Users\\93176\\AppData\\Local\\BypassRuntm;C:\\Program Files\\JetBrains\\PyCharm 2019.2.2\\bin;;E:\\software_install\\Opencv410_install\\opencv\\build\\x64\\vc15\\bin;C:\\Program Files\\NVIDIA Corporation\\NVSMI;C:\\Users\\93176\\AppData\\Local\\Microsoft\\WindowsApps;E:\\software_install\\cmake-3.15.3-win64-x64\\bin;C:\\Program Files (x86)\\Graphviz2.38\\bin;', 'PATHEXT': '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC', 'PROCESSOR_ARCHITECTURE': 'AMD64', 'PROCESSOR_IDENTIFIER': 'Intel64 Family 6 Model 158 Stepping 10, GenuineIntel', 'PROCESSOR_LEVEL': '6', 'PROCESSOR_REVISION': '9e0a', 'PROGRAMDATA': 'C:\\ProgramData', 'PROGRAMFILES': 'C:\\Program Files', 'PROGRAMFILES(X86)': 'C:\\Program Files (x86)', 'PROGRAMW6432': 'C:\\Program Files', 'PROMPT': '$P$G', 'PSMODULEPATH': 'C:\\Program Files\\WindowsPowerShell\\Modules;C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\Modules', 'PUBLIC': 'C:\\Users\\Public', 'PYCHARM': 'C:\\Program Files\\JetBrains\\PyCharm 2019.2.2\\bin;', 'SESSIONNAME': 'Console', 'SYSTEMDRIVE': 'C:', 'SYSTEMROOT': 'C:\\WINDOWS', 'TEMP': 'C:\\Users\\93176\\AppData\\Local\\Temp', 'TMP': 'C:\\Users\\93176\\AppData\\Local\\Temp', 'USERDOMAIN': 'SHLIANGPC', 'USERDOMAIN_ROAMINGPROFILE': 'SHLIANGPC', 'USERNAME': 'shl', 'USERPROFILE': 'C:\\Users\\93176', 'VS120COMNTOOLS': 'D:\\VS2013_install\\Common7\\Tools\\', 'WINDIR': 'C:\\WINDOWS'})
>>> print(type(os.environ))
<class 'os._Environ'>
>>>

1.1.5 os.curdir 屬性 :返回當前目錄"."

os.curdir: 返回當前目錄 (’.’)

  • 沒有參數,是屬性
  • 返回當前目錄
  • 返回類型是字符串

舉例:

>>> os.curdir
'.'
>>>

1.1.6 os.system(command):執行shell命令

os.system(command):執行shell命令

  • 是方法(函數)
  • 一個參數:
    • command :linux或windows命令行下的命令,傳入參數是字符串類型
  • 返回結果是整形int

舉例:

>>> print(type(os.system("chdir")))
C:\Users\93176
<class 'int'>
>>> print(type(os.system("time")))
當前時間: 16:11:55.85
輸入新時間:
<class 'int'>
>>>

1.1.7 os.listdir(path):返回一個當前路徑下文件和文件夾名稱的列表

os.listdir(path):返回一個當前路徑下文件和文件夾名稱的列表

  • 是方法(函數)
  • 一個參數:
    • path:傳入的是一個文件夾的路徑,傳入參數字符串類型
  • 返回類型是當前路徑下文件的的列表

舉例:

>>> import os
>>> os.listdir("./Public")
['AccountPictures', 'Desktop', 'desktop.ini', 'Documents', 'Downloads', 'Foxit Software', 'Libraries', 'Music', 'Pictures', 'QiYi', 'Thunder Network', 'Videos', 'Win']
>>>

1.1.8 os.getcwd():獲取當前的文件的所在的路徑

os.getcwd():獲取當前的文件的所在的路徑

  • 是方法(函數)
  • 沒有參數
    • 返回的是當前的文件所在的路徑
  • 返回結果是字符串類型

舉例:

>>> os.getcwd()
'C:\\Users'
>>>

1.1.9 os.mkdir(path) 創建一個目錄

`os.mkdir(path):· 創建一個目錄

  • 是方法(函數)
  • 一般用到的只有第一個參數
  • path:要創建的文件夾名字,傳入參數是字符串類型
  • 沒有返回值
    舉例:
os.mkdir(path)

在這裏插入圖片描述

1.1.10 os.makedirs(name):遞歸的創建文件夾

os.makedirs(name):遞歸的創建文件夾

  • os.makedirs(name, mode=511, exist_ok=False)
  • 是方法(函數)
  • 一般使用的參數有兩個:
    • name: 要遞歸的創建的文件夾,傳入字符串類型,例如“./test1/test2/test3” 創建3個文件夾
    • exist_ok:如果設置爲False,當要創建的文件夾已經存在就會報錯,如果設置爲True,當要創建的文件夾已經存在此時不創建,但也不會報錯提醒。
  • 沒有返回值

舉例:

os.makedirs("./test1/test2/test3", mode=511, exist_ok=True)

1.1.11 os.remove(path):指定刪除某個文件

os.remove(path):指定刪除某個文件

  • 是方法(函數)
  • 一個參數:
    • path:要刪除的文件
  • 沒有返回值
  • 不可以用於刪除目錄

舉例:

os.remove("os/hello/aa.txt")

1.2.12 os.rmdir(dirname):指定刪除某個文件夾

os.rmdir(dirname):指定刪除某個文件

  • 是方法(函數)
  • 一個參數:
    • dirname_path:要刪除的文件夾
  • 沒有返回值
  • 不可以用於刪除目錄

舉例:

os.rmdir("./os/hello")

刪除多個目錄:os.removedirs()

1.1.13 os.chdir(dirname) : 改變工作目錄到dirname

os.chdir(dirname): 改變工作目錄到dirname

  • 是方法(函數)
  • 一個參數:
    • dirname:傳入的是要改變到指定的文件夾路徑
  • 沒有返回結果

舉例:

>>> os.getcwd()
'C:\\Users\\93176\\Desktop'
>>> os.chdir("./test1/test2")
>>> os.getcwd()
'C:\\Users\\93176\\Desktop\\test1\\test2'
>>>

1.1.14os.getenv() 獲取一個環境變量,如果沒有返回none

os.getenv():
os.getenv(key, default=None)
os.system(command):執行shell命令

  • 是方法(函數)
  • 一個參數:
    • key 環境變量名,返回的是環境變量對應的值
  • 返回結果是字符串類型,如果變量不存在就返回None

舉例:

>>> print(os.getenv("HOMEPATH"))
\Users\93176
>>> print(os.getenv("shliang"))
None
>>>

1.1.15 os.putenv(key, value) 設置一個環境變量值

os.putenv: 設置一個環境變量值

舉例:

os.putenv("HOME2", "/users/93176/desktop")

1.1.16 os.walk()

os.walk(top, topdown=True, onerror=None, followlinks=False):

1.1.17 其他一些不帶path

  • os.rename(old, new) :重命名
  • os.stat(file) :獲取文件屬性
  • os.chmod(file) :修改文件權限與時間戳
  • os.get_terminal_size():獲取當前終端大小
  • os.kill():os.kill(pid, signal, /) 殺死進程,例如:
    os.kill(10884,signal.SIGKILL)

1.2 os帶path (os.path)

1.2.1 os.path.exists(path):檢驗給出的路徑是否存在

  • 返回布爾值,如果路徑存在則返回True,如果路徑不存在則放回Fale。
  • 這個路徑可以是文件,也可以是文件夾

舉例:

print(os.path.exists("./os/test"))
print(os.path.exists("./os/aa.txt"))
# 結果
True
True

1.2.2 os.path.isfile(filename):檢驗給出的路徑是否是一個文件

  • 存在返回布爾值 True,否則返回Fase。

舉例:

print(os.path.isfile("./os/aa.txt"))
# 結果
True

1.2.3 os.path.isdir(dirname):檢驗給出的路徑是否是一個目錄

  • 存在返回布爾值True,否則返回Fase。

舉例:

print(os.path.isdir("./os/test"))
# 結果
True

1.2.4 os.path.isabs():判斷是否是絕對路徑

  • 是絕對路徑返回True,否則返回False

舉例:

print(os.path.isabs("./os/aa.txt"))
print(os.path.isabs(r"C:\\Users\\93176\\Desktop/test1.txt"))
# 結果
False
True

1.2.5 os.path.join():把文件和路徑合成一個名, 用來拼接全名

  • 用於路徑的拼接

舉例:

print(os.path.join("C:/Users/93176/", "test1"))
print(os.path.join("C:/Users/93176/", "test1", "test2", "test3"))
# 結果
C:/Users/93176/test1
C:/Users/93176/test1\test2\test3

1.2.6 os.path.basename():獲取文件名

  • 返回path最後的文件名。如果path以/或\結尾,那麼就會返回空值。即os.path.split(path)的第二個元素。
  • 只有路徑最後是文件名纔會返回文件名,否則就什麼也不返回

舉例:

print(os.path.basename("./os/aa.txt"))
print(os.path.basename("./os/"))
# 結果
aa.txt

1.2.7 os.path.dirname():獲取文件所在的路徑名

  • 獲取文件所在的路徑名,如果 傳入的路徑是文件夾,則返回的路徑和傳入一樣
  • 如果傳入的是文件,則返回的是文件所在的文件夾路徑

舉例:

print(os.path.dirname("./os/test/"))
print(os.path.dirname("./os/aa.txt"))
# 結果
./os/test
./os

1.2.8 os.path.abspath():獲得相對路徑的絕對路徑

  • 返回的是傳入相對路徑的絕對路徑
  • 返回值的類型是字符串
    舉例:
print(os.path.abspath("./os/test/"))
print(os.path.abspath("./os/aa.txt"))
# 結果
C:\Users\93176\Desktop\os\test
C:\Users\93176\Desktop\os\aa.txt

1.2.9 os.path.split():返回一個路徑的目錄名和文件名

  • 返回結果是一個元組類型

舉例:

print(os.path.split("./os/aa.txt"))
# 結果
('./os', 'aa.txt')

1.2.10 os.path.splitext():分離擴展名

  • 返回結果是一個元組類型

舉例:

print(os.path.splitext("./os/aa.txt"))
# 結果
('./os/aa', '.txt')

1.2.11 os.path.getsize(filename):返回文件的大小

  • 返回文件的大小,單位是字節

aa.txt 中的內容爲 :hello 一個字符佔一個字節
舉例:

print(os.path.getsize("./os/aa.txt"))
# 結果
5

2 shutil模塊使用

2.1 shutil模塊文件基本使用

2.1.1 shutil.move(src, dst) 移動文件 或 目錄.(也可以重命名)

  • 把src,移動到dst的位置
  • 返回文件被移動後的路徑
  • 不僅可以移動文件,同樣文件夾也可以被移動
  • dst中一定不可以有 src同名的文件或文件夾,否則會報錯,dst已經存在src
  • 移動到dst的文件和目錄頁可以重命名
  • src被從原來的路徑移走就已經不存在啦

舉例:

shutil.move("./shutil/test1/aa.txt", "./shutil/test2/")
shutil.move("./shutil/test1/test11", "./shutil/test2/")
shutil.move("./shutil/test1/aa.txt", "./shutil/test2/cc.txt")  # 重命名
# 結果
'C:\\\\Users\\\\93176\\\\Desktop/test2.txt'
'./shutil/test2/test11'
'./shutil/test2/cc.txt'

2.1.2 shutil.

2.2 shutil模塊的拷貝

2.2.1 shutil.copyfile(oldfile, newfile)

  • shutil.copy(src, dst, *, follow_symlinks=True)
  • oldfile只能是文件夾,newfile可以是文件,也可以是目標目錄
  • 和shutil.copyfile()類似

舉例:

shutil.copy("./shutil/test1/aa.txt", "./shutil/test2/")
shutil.copy("./shutil/test1/aa.txt", "./shutil/test2/")   # 這個就類似shutil.move()
# 結果
'./shutil/test2/cc.txt'
'./shutil/test2/aa.txt'

2.2.2 shutil.copyfile(oldfile, newfile)

  • shutil.copyfile(src, dst, *, follow_symlinks=True)
  • src和dst都必須是文件
  • src文件中的內容會覆蓋dst文件中的內容,但是dst的文件名不變
  • 因爲只是拷貝,所有src的文件不變
  • 返回的是拷貝後文件dst文件的路徑
    舉例:
shutil.copyfile("./shutil/test1/aa.txt", "./shutil/test2/bb.txt")
# 結果
'./shutil/test2/bb.txt'

2.2.3 shutil.copytree(olddir, newdir): 遞歸的去拷貝文件夾

  • shutil.copytree(src, dst, symlinks=False, ignore=None, copy_function=<function copy2 at 0x0000022C44A3BE18>, ignore_dangling_symlinks=False)
  • olddir和newdir都只能是目錄,且newdir必須不存在

2.2.3 shutil.rmtree(src):

  • shutil.rmtree( src ) 遞歸刪除一個目錄以及目錄內的所有內容
    舉例:

# 結果

2.3.4 其他拷貝相關

shutil.copymode( src, dst) : 只是會複製其權限其他的東西是不會被複制的
shutil.copystat( src, dst) : 複製權限、最後訪問時間、最後修改時間
shutil.copy2( src, dst) : 在copy上的基礎上再複製文件最後訪問時間與修改時間也複製過來了,類似於cp –p的東西
shutil.copy2( src, dst) : 如果兩個位置的文件系統是一樣的話相當於是rename操作,只是改名;如果是不在相同的文件系統的話就是做move操作
shutil.copytree( olddir, newdir, True/Flase)
把olddir拷貝一份newdir,如果第3個參數是True,則複製目錄時將保持文件夾下的符號連接,如果第3個參數是False,則將在複製的目錄下生成物理副本來替代符號連接

3 附錄:

3.1 查看python中模塊的所有方法

導入模塊之後,可以在命令行中查看模塊的所有方法

3.1.1 使用dir(modulename)進行查看

dir()其實有很多種使用姿勢,主要如下,讓我們來一一進行解鎖吧!

  • 查看模塊的方法和屬性名
  • 查看模塊的子類的方法和屬性
  • 查看數據類型的方法和屬性

1、查看模塊的方法和屬性

dir(modulename):列出模塊中定義的所有函數(方法)變量名稱

如下:
在這裏插入圖片描述

>>> import os
>>> dir(os)
['DirEntry', 'F_OK', 'MutableMapping', 'O_APPEND', 'O_BINARY', 'O_CREAT', 'O_EXCL', 'O_NOINHERIT', 'O_RANDOM', 'O_RDONLY', 'O_RDWR', 'O_SEQUENTIAL', 'O_SHORT_LIVED', 'O_TEMPORARY', 'O_TEXT', 'O_TRUNC', 'O_WRONLY', 'P_DETACH', 'P_NOWAIT', 'P_NOWAITO', 'P_OVERLAY', 'P_WAIT', 'PathLike', 'R_OK', 'SEEK_CUR', 'SEEK_END', 'SEEK_SET', 'TMP_MAX', 'W_OK', 'X_OK', '_Environ', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_execvpe', '_exists', '_exit', '_fspath', '_get_exports_list', '_putenv', '_unsetenv', '_wrap_close', 'abc', 'abort', 'access', 'altsep', 'chdir', 'chmod', 'close', 'closerange', 'cpu_count', 'curdir', 'defpath', 'device_encoding', 'devnull', 'dup', 'dup2', 'environ', 'errno', 'error', 'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe', 'extsep', 'fdopen', 'fsdecode', 'fsencode', 'fspath', 'fstat', 'fsync', 'ftruncate', 'get_exec_path', 'get_handle_inheritable', 'get_inheritable', 'get_terminal_size', 'getcwd', 'getcwdb', 'getenv', 'getlogin', 'getpid', 'getppid', 'isatty', 'kill', 'linesep', 'link', 'listdir', 'lseek', 'lstat', 'makedirs', 'mkdir', 'name', 'open', 'pardir', 'path', 'pathsep', 'pipe', 'popen', 'putenv', 'read', 'readlink', 'remove', 'removedirs', 'rename', 'renames', 'replace', 'rmdir', 'scandir', 'sep', 'set_handle_inheritable', 'set_inheritable', 'spawnl', 'spawnle', 'spawnv', 'spawnve', 'st', 'startfile', 'stat', 'stat_float_times', 'stat_result', 'statvfs_result', 'strerror', 'supports_bytes_environ', 'supports_dir_fd', 'supports_effective_ids', 'supports_fd', 'supports_follow_symlinks', 'symlink', 'sys', 'system', 'terminal_size', 'times', 'times_result', 'truncate', 'umask', 'uname_result', 'unlink', 'urandom', 'utime', 'waitpid', 'walk', 'write']
>>>

2、查看模塊的子類的方法和屬性
如果你想要查看os.path下有哪些方法和屬性可以使用,同樣可以用dir進行查看

dir(os.path)

在這裏插入圖片描述

>>> dir(os.path)
['__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_get_bothseps', '_getfinalpathname', '_getfullpathname', '_getvolumepathname', 'abspath', 'altsep', 'basename', 'commonpath', 'commonprefix', 'curdir', 'defpath', 'devnull', 'dirname', 'exists', 'expanduser', 'expandvars', 'extsep', 'genericpath', 'getatime', 'getctime', 'getmtime', 'getsize', 'isabs', 'isdir', 'isfile', 'islink', 'ismount', 'join', 'lexists', 'normcase', 'normpath', 'os', 'pardir', 'pathsep', 'realpath', 'relpath', 'samefile', 'sameopenfile', 'samestat', 'sep', 'split', 'splitdrive', 'splitext', 'splitunc', 'stat', 'supports_unicode_filenames', 'sys']
>>>

3、查看數據類型的方法和屬性

比如有些字符串的屬性和方法你記不清楚了,你就可以通過如下的方法進行查看

dir("Hello")
在這裏插入圖片描述

>>> dir("Hello world")
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>>

同理你也可以使用dir([]) dir({}) 等數據類型有哪些方法和屬性

3.2 查看python種模塊、方法和屬性的使用文檔

上面使用dir() 主要是查看有哪些方法屬性,如果想要知道某個方法的具體介紹和使用文檔應該怎麼版呢,別急,下面我們來一起解鎖吧!

使用方法: help(modulename)

  • 查看模塊的使用文檔
  • 查看模塊的某個方法或屬性的介紹與使用

1、查看模塊的使用文檔

help(os)

在這裏插入圖片描述

>>> help(os)
Help on module os:

NAME
    os - OS routines for NT or Posix depending on what system we're on.

DESCRIPTION
    This exports:
      - all functions from posix or nt, e.g. unlink, stat, etc.
      - os.path is either posixpath or ntpath
      - os.name is either 'posix' or 'nt'
      - os.curdir is a string representing the current directory (always '.')
      - os.pardir is a string representing the parent directory (always '..')
      - os.sep is the (or a most common) pathname separator ('/' or '\\')
      - os.extsep is the extension separator (always '.')
      - os.altsep is the alternate pathname separator (None or '/')
      - os.pathsep is the component separator used in $PATH etc
      - os.linesep is the line separator in text files ('\r' or '\n' or '\r\n')
      - os.defpath is the default search path for executables
      - os.devnull is the file path of the null device ('/dev/null', etc.)

    Programs that import and use 'os' stand a better chance of being
    portable between different platforms.  Of course, they must then
    only use functions that are defined by all platforms (e.g., unlink
    and opendir), and leave all pathname manipulation to os.path
    (e.g., split and join).

CLASSES
    builtins.Exception(builtins.BaseException)
        builtins.OSError
    builtins.object
        nt.DirEntry
    builtins.tuple(builtins.object)
        nt.times_result
        nt.uname_result
        stat_result
        statvfs_result
        terminal_size
-- More  --

文檔內動過多,如果要退出查看,按快捷鍵 Ctrl + C

2、 查看模塊的某個方法或屬性的介紹與使用

dir(os.path.join)

在這裏插入圖片描述

>>> help(os.path.join)
Help on function join in module ntpath:

join(path, *paths)
    # Join two (or more) paths.

>>>

注意:

dir() 和 help() 傳入的模塊、方法、屬性,也可以是字符串的形式,結果一樣,例如:help("os.path.join")

參考:
1、https://blog.csdn.net/u011961856/article/details/79122057
2、https://blog.csdn.net/silentwolfyh/article/details/74931123
3、https://blog.csdn.net/seanblog/article/details/78885423
4、https://blog.csdn.net/CloudXli/article/details/79421599
5、http://www.codexiu.cn/python/blog/12183/

在這裏插入圖片描述


在這裏插入圖片描述


在這裏插入圖片描述
♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章