一、os.listdir()-列出路徑下的文件和目錄名
import os path = './' # 當前路徑 dirs = os.listdir(path) # 遍歷輸出所有文件名和目錄名 for file in dirs: print(file)
os.listdir()函數用於從指定路徑中獲取包含的文件或目錄的列表。 在這個例子中,我們定義了當前路徑path='./'
,並用os.listdir()
函數獲取這個路徑下的所有文件和文件夾的名稱,然後通過遍歷這個列表輸出所有的名稱。
二、os.path.isfile()-判斷路徑是否為文件
import os file_path = './example.txt' if os.path.isfile(file_path): print(file_path + ' is a file') else: print(file_path + ' is not a file')
os.path.isfile()
函數用於判斷指定路徑是否是一個文件。 這個例子中,我們定義了路徑file_path='./example.txt'
,然後用os.path.isfile()
函數判斷這個路徑是否為一個文件。
三、os.path.isdir()-判斷路徑是否為目錄
import os dir_path = './example_dir/' if os.path.isdir(dir_path): print(dir_path + ' is a directory') else: print(dir_path + ' is not a directory')
os.path.isdir()
函數用於判斷指定路徑是否是一個目錄。 在這個例子中,我們定義了路徑dir_path='./example_dir/'
,然後用os.path.isdir()
函數判斷它是否為一個目錄。
四、os.path.exists()-判斷路徑是否存在
import os path = './example.txt' if os.path.exists(path): print(path + ' exists') else: print(path + ' does not exist')
os.path.exists()
函數用於判斷指定路徑是否存在。 在這個例子中,我們定義了路徑path='./example.txt'
,然後用os.path.exists()
函數判斷它是否存在。
五、os.walk()-遍歷目錄樹
import os path = './example_dir/' # 遍歷打印目錄樹 for root, dirs, files in os.walk(path): print('root:', root) print('dirs:', dirs) print('files:', files)
os.walk()
函數用於生成目錄樹中每一個目錄下的所有文件名和目錄名。 在這個例子中,我們定義了目錄path='./example_dir/'
,然後用os.walk()
函數生成目錄樹並打印輸出目錄樹下每一個目錄的名稱、該目錄下的所有文件夾和文件的名稱。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/286289.html