3 回答

TA貢獻1155條經(jīng)驗 獲得超0個贊
問題是您試圖從與您列出的目錄不同的目錄中打開相對文件路徑。與其使用os它,不如使用一個更高級別的接口,例如pathlib:
import pathlib
for file_name in pathlib.Path("/Users/ramikhoury/PycharmProjects/R/excel_files").glob("*.xslx"):
# this produces full paths for you to use
pathlib是在Python 3.4中添加的,因此,如果您使用的是舊版本的python,則最好的選擇是使用更老的glob模塊,該模塊的功能類似:
import glob
for file_name in glob.glob("/Users/ramikhoury/PycharmProjects/R/excel_files/*.xslx"):
# this also produces full paths for you to use
如果出于某種原因您確實需要使用低級os接口,則解決此問題的最佳方法是使用對以下dir_fd參數(shù)的可選參數(shù)open:
# open the target directory
dir_fd = os.open("/Users/ramikhoury/PycharmProjects/R/excel_files", os.O_RDONLY)
try:
# pass the open file descriptor to the os.listdir method
for file_name in os.listdir(dir_fd):
# you could replace this with fnmatch.fnmatch
if file_name.endswith(".xlsx"):
# use the open directory fd as the `dir_fd` argument
# this opens file_name relative to your target directory
with os.fdopen(os.open(file_name, os.O_RDONLY, dir_fd=dir_fd)) as file_:
# do excel bits here
finally:
# close the directory
os.close(dir_fd)
盡管可以通過更改腳本頂部的目錄來完成此修復(如另一個答案所建議),但這具有更改進程的當前工作目錄的副作用,這通常是不希望的,并且可能會帶來負面影響。為了使這項工作沒有副作用,需要您chdir返回到原始目錄:
# store cwd
original_cwd = os.getcwd()
try:
os.chdir("/Users/ramikhoury/PycharmProjects/R/excel_files")
# do your listdir, etc
finally:
os.chdir(original_cwd)
請注意,這會在您的代碼中引入競爭條件,original_cwd可能會被刪除,或者可能更改了該目錄的訪問控制,從而使您無法chdir返回到目錄,這正是dir_fd存在的原因。
dir_fd是在Python 3.3中添加的,因此,如果您使用的是舊版本的Python,我建議您僅使用glob而不是chdir解決方案。
添加回答
舉報