Pin-Jiun / Python

Python Document
0 stars 0 forks source link

23-glob #23

Open Pin-Jiun opened 1 year ago

Pin-Jiun commented 1 year ago

glob.glob(pathname, *, recursive=False) 會返回一個list, list裡面會包含你搜尋到符合你資格的file, dir

  1. 首先,為了示範方便,先來建立一些資料夾
    
    import os
    import glob

Create directory

os.mkdir(os.path.join("Folder_1") os.mkdir(os.path.join("Folder_1", "File_1.txt")) os.mkdir(os.path.join("Folder_1", "File_2.csv")) os.mkdir(os.path.join("Folder_1", "File_3.txt"))

備註:這邊其實都是建立資料夾,只是為了示範用,所以加上檔名,實際上並非檔案


2. 試著利用 glob.glob 來讀取檔案路徑, 可以使用`萬用字元`(注意, 不是正規表達式)

數 pathname 用到的一些符號:

`*` 的意思就是匹配所有的內容
可以自己設定要讀什麼檔案類型,像是:.txt, .csv
也可以再進一步針對檔名的變化設定,像是:[1-2] 就是匹配 1 到 2 之間的整數數值

```py
# Find pathnames under the specified directory 

# 取得 Folder_1 這層裡面,所有東西的路徑
print(glob.glob(os.path.join("Folder_1", "*"))) 

# 取得 Folder_1 這層裡面,結尾是 .txt 的路徑
print(glob.glob(os.path.join("Folder_1", "*.txt")))

# 取得 Folder_1 這層裡面,結尾是 .csv 的路徑
print(glob.glob(os.path.join("Folder_1", "*.csv")))

# 取得 Folder_1 這層裡面,檔名中有 1 或 2 的東西的路徑
print(glob.glob(os.path.join("Folder_1", "*[1-2]*")))

# 備註
# 這邊利用 os.path.join 來連接指定字串形成路徑,因為不同系統下的分隔符號可能不同
# 可以用 os.sep 來查看,在設定路徑時,也直接用符合的分隔符號來串連
['Folder_1/File_1.txt', 'Folder_1/File_3.txt', 'Folder_1/File_2.csv']
['Folder_1/File_1.txt', 'Folder_1/File_3.txt']
['Folder_1/File_2.csv']
['Folder_1/File_1.txt', 'Folder_1/File_2.csv']

https://ithelp.ithome.com.tw/articles/10262521

Pin-Jiun commented 1 year ago

讀取多個檔案也可以使用

import tkinter as tk
from tkinter import filedialog
import os

def get_the_folder_path():
    root = tk.Tk()
    root.withdraw()
    folder_path = filedialog.askdirectory()
    print(folder_path)
    return folder_path  

#read mutiple files from a Folder to a list
def get_mutiple_files_name_list():
    folder_path = get_the_folder_path()
    files_list= os.listdir(folder_path) #get the all file list
    return files_list