考慮我的檔案夾結構具有以下方式的檔案:-
abc.csv
abc.json
bcd.csv
bcd.json
efg.csv
efg.json
依此類推,即一對具有相同名稱的 csv 檔案和 json 檔案,我必須通過讀取相同的命名檔案來執行相同的操作,執行一些操作并繼續下一對檔案。我該怎么做?基本上我想到的偽代碼是:-
for files in folder_name:
df_csv=pd.read_csv('abc.csv')
df_json=pd.read_json('abc.json')
# some script to execute
#now read the next pair and repeat for all files
uj5u.com熱心網友回復:
你想過這樣的事情嗎?
import os
# collects filenames in the folder
filelist = os.listdir()
# iterates through filenames in the folder
for file in filelist:
# pairs the .csv files with the .json files
if file.endswith(".csv"):
with open(file) as csv_file:
pre, ext = os.path.splitext(file)
secondfile = pre ".json"
with open(secondfile) as json_file:
# do something
uj5u.com熱心網友回復:
如果目錄結構一致,您可以執行以下操作:
import os
for file_name in {x.split('.')[0] for x in os.listdir('./path/to/dir')}:
df_csv = pd.read_csv("{f_name}.csv")
df_json = pd.read_json("{f_name}.json")
# execute the rest
uj5u.com熱心網友回復:
您可以使用該glob模塊來提取與模式匹配的檔案名:
import glob
import os.path
for csvfile in glob.iglob('*.csv'):
jsonfile = csvfile[:-3] 'json'
# optionaly control file existence
if not os.path.exists(jsonfile):
# show error message
...
continue
# do smth. with csvfile
# do smth. else with jsonfile
# and proceed to next pair
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/519743.html
下一篇:col內的值計數
