我想對與我的腳本位于同一文件夾中且符合命名約定的所有文件執行一些數據清理。數據清理我很好,但它只是我正在努力解決的同一個文件夾。以前的工作代碼:import glob
for filename in glob.glob('C:/Users/<me>/Downloads/New Folder/Forecast and Inventory *.xlsx'):當前代碼:import os
for filename in os.getcwd() + '\Forecast and Inventory *.xlsx':我得到錯誤代碼No such file or directory: 'C'我是否需要進行某種替換才能將 \s 轉換為 /s?正如代碼所示,我想要所有以“預測和庫存”開頭的文件。謝謝!
1 回答

幕布斯7119047
TA貢獻1794條經驗 獲得超8個贊
您正在遍歷一個字符串。
因為os.getcwd() + '\Forecast and Inventory *.xlsx'是字符串"C://**working-dir/Forecast and Inventory *.xlsx"
所以第一次迭代filename是字符串'C'。
例如
for filename in os.getcwd() + '\Forecast and Inventory *.xlsx':
print(filename)
將返回
"C"
":"
"/"
...
你只需要把路徑放在里面glob.glob
for filename in glob.glob(os.getcwd() + '\Forecast and Inventory *.xlsx'):
# do something
添加回答
舉報
0/150
提交
取消