在 for 循环中收到 "no such file or directory" 错误 - 最初识别文件
Receiving "no such file or directory" error within a for loop - recognizes file initially
代码如下:
for WorkingFile in os.listdir(path):
print(WorkingFile)
xlsx = pd.ExcelFile(WorkingFile)
returns这个:
ChetworthPark_Test.xlsx
FileNotFoundError: [Errno 2] No such file or directory: 'ChetworthPark_Test.xlsx'
所以它打印文件名(证明它识别路径),但之后没有将它传递给变量“xlsx”。关于我哪里出错的任何想法?有关更多上下文,我是 运行 Google Colab 中的这个。
os.listdir
returns 文件名 不是路径。所以你需要在路径前添加:
for fn in os.listdir(path):
do_something(f"{path}/{fn}")
正如评论中指出的那样,路径的 /
不是通用的,因此我们有 os.path.join
:
from os.path import join
for fn in os.listdir(path):
fn = join(path, fn) # handles / or \
do_something(fn)
然而,现在我们已经有一段时间了 pathlib.Path
,这让这变得容易多了:
from pathlib import Path
for fn in os.listdir(path):
do_something(Path(path) / fn)
或者,更自然地使用 pathlib:
from pathlib import Path
for fn in Path("/path/to/look/at").expanduser().resolve().glob("*"):
if not fn.is_file():
continue
do_something(fn)
(请注意,我还处理了 ~/some-file
之类的扩展并简化了此处的路径)
代码如下:
for WorkingFile in os.listdir(path):
print(WorkingFile)
xlsx = pd.ExcelFile(WorkingFile)
returns这个:
ChetworthPark_Test.xlsx
FileNotFoundError: [Errno 2] No such file or directory: 'ChetworthPark_Test.xlsx'
所以它打印文件名(证明它识别路径),但之后没有将它传递给变量“xlsx”。关于我哪里出错的任何想法?有关更多上下文,我是 运行 Google Colab 中的这个。
os.listdir
returns 文件名 不是路径。所以你需要在路径前添加:
for fn in os.listdir(path):
do_something(f"{path}/{fn}")
正如评论中指出的那样,路径的 /
不是通用的,因此我们有 os.path.join
:
from os.path import join
for fn in os.listdir(path):
fn = join(path, fn) # handles / or \
do_something(fn)
然而,现在我们已经有一段时间了 pathlib.Path
,这让这变得容易多了:
from pathlib import Path
for fn in os.listdir(path):
do_something(Path(path) / fn)
或者,更自然地使用 pathlib:
from pathlib import Path
for fn in Path("/path/to/look/at").expanduser().resolve().glob("*"):
if not fn.is_file():
continue
do_something(fn)
(请注意,我还处理了 ~/some-file
之类的扩展并简化了此处的路径)