我打算從嵌套檔案目錄中讀取具有特定模式的 csv 檔案,其中每個子目錄都有多個 csv 檔案,我只想讀取具有特定模式的一端。我已經想出了在 R 中執行此操作的方法,但想在 pandas 中執行此操作。我發現了一些有用的帖子,但無法讀取我想在 pandas 中讀取的檔案。
當前嘗試
這是我擁有并想讀取以 Z_19_xx.csv 開頭的檔案的檔案結構。例如:
import pandas as pd
dir1="demo2020/p1 pop/csv/Z_19_master.csv"
f1=pd.read_csv(dir1)
這是硬編碼的,我想避免這樣做。下面是檔案結構:
demo2020
- p1 pop
-csv
- A_17_master.csv
- A_18_master.csv
- B_18_master.csv
- C_19_master.csv
- Z_19_master.csv
- p2 cop
-csv
- A_17_cop.csv
- A_18_cop.csv
- B_18_cop.csv
- C_19_cop.csv
- Z_19_cop.csv
- p3 res
-csv
- A_17_res.csv
- A_18_res.csv
- B_18_res.csv
- C_19_res.csv
- Z_19_res.csv
- p4 nac
-csv
- A_17_nac.csv
- A_18_nac.csv
- B_18_nac.csv
- C_19_nac.csv
- Z_19_nac.csv
我目前在 R 中的嘗試:
這是我的 R 代碼,可以方便地執行此操作:
yr=19
dir="demo2020/"
files <-c(f1 = paste0("p1 pop/csv/Z_", yr, "_master.csv") ,
f2 = paste0('p2 cop/csv/Z_', yr,'_cop.csv') ,
f3 = paste0('p3 res/csv/Z_', yr,'_res.csv') ,
f4 = paste0('p4 nac/csv/Z_', yr,'_nac.csv')
)
path=(paste0(dir,files))
> path
[1] "demo2020/p1 pop/csv/Z_19_master.csv"
[2] "demo2020/p2 cop/csv/Z_19_cop.csv"
[3] "demo2020/p3 res/csv/Z_19_res.csv"
[4] "demo2020/p4 nac/csv/Z_19_nac.csv"
# read them
for(i in 1:length(files))
{
f <- assign(names(files[i]), read.csv(paste0(dir, files[i]),stringsAsFactors = FALSE,skip = 1))
}
蟒蛇目標 - 熊貓
我想在沒有硬編碼的情況下在 python 中執行此操作,并且只想在 python 中使用上述 R 代碼邏輯并使用 pandas 來讀取 csv 檔案。到目前為止,這是我的嘗試:
import pandas
import os
parent_dir = 'demo2020/'
subject_dirs = [os.path.join(parent_dir, dir) for dir in os.listdir(parent_dir) if os.path.isdir(os.path.join(parent_dir, dir))]
filelist = []
for dir in subject_dirs:
csv_files = [os.path.join(dir, csv) for csv in os.listdir(dir) if os.path.isfile(os.path.join(dir, csv)) and and csv.startswith('Z_') and csv.endswith('.csv')]
for file in csv_files:
df=pd.read_csv(file)
filelist.append(df)
但仍然沒有做到這一點,我只想Z_19_xx.csv從每個子檔案夾中讀取并將它們連接起來。我們如何在 python 中很好地做到這一點?誰能指出我不要在python中做到這一點?任何想法?
uj5u.com熱心網友回復:
您可以使用glob模式來匹配檔案:demo2020/p*/csv/Z_*.csv
import glob
csv_files = glob.glob('demo2020/p*/csv/Z_*.csv')
filelist = []
for file in csv_files:
df = pd.read_csv(file)
filelist.append(df)
uj5u.com熱心網友回復:
您可以使用 Glob() 函式在 Python 中遞回查找檔案。使用 glob,除了精確的字串搜索,我們還可以使用通配符(“*, ?, [ranges])來使路徑檢索更加簡單方便。
如果要匹配檔案:Z_19_xx.csv 而不是 Z_xx.csv,可以使用以下內容:
import glob
csv_files = glob.glob('demo2020/p*/csv/Z_19_*.csv')
filelist = []
for file in csv_files:
df = pd.read_csv(file)
filelist.append(df)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/431722.html
上一篇:水平折疊某些列
