OS模塊經常使用方法

os模塊提供了多數操做系統的功能接口函數,當os模塊被導入後,它會自適應於不一樣的操做系統平臺,根據不一樣的平臺進行相應的操做。html

getcwd() 方法

getcwd()方法用於返回當前進程的工做目錄。python

語法:os.getcwd()

示例:ide

import os
print(os.getcwd())

# C:\Users\lu\testfile

listdir()方法

listdir() 方法用於返回指定的文件夾包含的文件或文件夾的名字的列表。列表以字母順序。函數

語法:os.listdir(path)

path爲須要列出的目錄路徑

示例:idea

import os

path = "C:/Users/lu/xxx"  # 路徑
lst = os.listdir(path)

# 輸出全部文件和文件夾
for i in lst:
    print(i)

'''
.idea
blog
haha
manage.py
templates
testfile
venv
'''

remove() 方法

remove() 方法用於刪除指定路徑的文件。若是指定的路徑是一個目錄,將拋出OSError異常。該方法沒有返回值。操作系統

語法:os.remove(path)

path 爲要移除的文件路徑

示例:code

import os
# 先查看目錄中全部文件
print(os.listdir(os.getcwd()))  # ['examination.xls', 'test.py', 'test.txt']

# 移除指定文件
os.remove("test.txt")

# 查看移除後的目錄
print(os.listdir(os.getcwd()))  # ['examination.xls', 'test.py']

rmdir()方法

rmdir() 方法用於刪除指定路徑的目錄。僅當這文件夾是空的才能夠刪除, 不然拋出OSError異常。htm

os.rmdir(path)

path爲 要刪除的目錄路徑

示例:blog

import os
# 查看目錄中全部的文件
print(os.listdir(os.getcwd()))  # ['directory', 'examination.xls', 'test.py', 'test.txt']

# 移除指定目錄
# os.rmdir('directory')

# 只能移除目錄,若是移除文件則會報錯
os.rmdir('test.txt')

# 查看移除後的目錄
print(os.listdir(os.getcwd()))  # ['examination.xls', 'test.py', 'test.txt']

removedirs()方法

removedirs() 方法用於刪除多層遞歸的空目錄。若目錄中有文件則沒法刪除。遞歸

os.removedirs(path)

path 要移除的目錄路徑

示例:

import os
# 查看目錄中全部的文件
print(os.listdir(os.getcwd()))  # ['mki','test.py', 'test.txt']

# 移除指定目錄
os.removedirs('mki')

# 查看移除後的目錄
print(os.listdir(os.getcwd()))  # ['test.py', 'test.txt']

mkdir() 方法

mkdir() 方法用於以數字權限模式建立目錄。默認的模式爲 0777 (八進制)。

語法:os.mkdir(path[, mode])

path 爲要建立的目錄
mode 要爲目錄設置的權限數字模式

示例:

import os

# 建立目錄
path = 'C:/Users/lu/PycharmProjects/haha/testfile/mki'

os.mkdir(path)

print("目錄已建立")

makedirs() 方法

makedirs() 方法用於遞歸建立目錄,相似mkdir()方法,但建立的全部intermediate-level文件夾須要包含子目錄。

語法:os.makedirs(path, mode=0o777)

path 須要遞歸建立的目錄
mode 權限模式

示例:

import os

path = "C:/Users/lu/PycharmProjects/haha/eefile/aa"
os.makedirs(path, 0o777)
print ("路徑被建立")

chdir() 方法

chdir() 方法用於改變當前工做目錄到指定的路徑。

語法:os.chdir(path)

path 爲要切換到的新路徑

示例:

import os

# 查看當前工做目錄
print(os.getcwd())  # C:\Users\lu\PycharmProjects\haha\eefile

# 要切換到的新路徑
path = 'C:/Users/lu/PycharmProjects/haha/haha'

# 修改當前工做目錄
os.chdir(path)

# 查看修改後的工做目錄
print(os.getcwd()) # C:\Users\lu\PycharmProjects\haha\haha

參考:https://docs.python.org/3/library/os.html?highlight=os

參考:https://www.9xkd.com/

相關文章
相關標籤/搜索