我想根據條件從檔案夾中讀取 csv 檔案。我只想讀取檔案名中包含“1441”的 csv 檔案。我使用了 fnmatch,但它不起作用。任何人都可以幫忙嗎?
提前致謝
path_to_parent = r"C:\Users\Desktop\books/chapter_1"
for csv_file in os.listdir(path_to_parent):
if fnmatch.fnmatch(csv_file,'1441'):
my_file = pd.read_csv(path_to_parent csv_file)
else:
print('error')
uj5u.com熱心網友回復:
您需要使用通配符1441來匹配檔案名的其余部分。否則它正在尋找確切的檔案名1441。
此外,您不會在連接它們之間path_to_parent和csv_file連接它們時添加目錄分隔符。最好os.path.join()用于便攜性。
for csv_file in os.listdir(path_to_parent):
if fnmatch.fnmatch(csv_file,'*1441*'):
my_file = pd.read_csv(os.path.join(path_to_parent, csv_file))
else:
print('error')
我也建議glob.glob()改用。它將為您進行通配符匹配,并將回傳完整路徑,因此您不必每次都通過回圈連接。
for csv_file in glob.glob(os.path.join(path_to_parent, '*1441*')):
my_file = pd.read_csv(csv_file)
uj5u.com熱心網友回復:
您可以嘗試不同的方法,對 if 陳述句稍作修改。
for csv_file in os.listdir(path_to_parent):
if '1441' in csv_file:
my_file = pd.read_csv(f'{path_to_parent}/{csv_file}')
else:
print('error')
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/490627.html
