简体   繁体   English

Python 错误 FileNotFoundError: [Errno 2] 没有这样的文件或目录:

[英]Python error FileNotFoundError: [Errno 2] No such file or directory:

Im trying to run my code with this but keep running into a file not found error.我试图用这个运行我的代码,但一直遇到文件未找到错误。

files = [i for i in os.listdir('C:/Users/me/Desktop/python data')]
for filename in files:    
    data = pandas.read_excel(str(filename))

I've tried looking around but cant seem to understand.我试过环顾四周,但似乎无法理解。

Running print(os.getcwd()) does find the file in the folder but i still get the error message运行print(os.getcwd())确实在文件夹中找到了文件,但我仍然收到错误消息

You need to concatenate the path and the filename returned from os.listdir :您需要连接从os.listdir返回的路径和文件名:

PATH = 'C:/Users/me/Desktop/python data'
files = [os.path.join(PATH, i) for i in os.listdir(PATH)]
for filename in files:
    data = pandas.read_excel(str(filename))

Further recommendations:进一步的建议:

  1. You can use pathlib 's .glob to get the full path without using os.path.join .您可以使用pathlib.glob来获取完整路径,而无需使用os.path.join
  2. Also, if you use read_excel , please consider filtering by xls/xlsx files:此外,如果您使用read_excel ,请考虑按 xls/xlsx 文件过滤:

Code example:代码示例:

import pathlib


path = pathlib.Path('C:/Users/me/Desktop/python data')
excel_filter = "*.xls*"
for filename in path.glob(excel_filter):
    print(filename)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python 错误 FileNotFoundError: [Errno 2] 没有这样的文件或目录 - Python Error FileNotFoundError: [Errno 2] No such file or directory FileNotFoundError: [Errno 2] 没有这样的文件或目录 Azure Python 错误 - FileNotFoundError: [Errno 2] No such file or directory Azure Python error Python 错误:FileNotFoundError: [Errno 2] 没有那个文件或目录 - Python error: FileNotFoundError: [Errno 2] No such file or directory FileNotFoundError: [Errno 2] 没有这样的文件或目录(python 错误) - FileNotFoundError: [Errno 2] No such file or directory (python error) Python: FileNotFoundError: [Errno 2] No such file or directory 错误 - Python: FileNotFoundError: [Errno 2] No such file or directory error python:FileNotFoundError:[Errno 2]没有这样的文件或目录 - python: FileNotFoundError: [Errno 2] No such file or directory Python FileNotFoundError:[错误2]没有这样的文件或目录 - Python FileNotFoundError: [Errno 2] No such file or directory Python FileNotFoundError: [Errno 2] 没有这样的文件或目录: - Python FileNotFoundError: [Errno 2] No such file or directory: Python 3-FileNotFoundError:[Errno 2]没有这样的文件或目录 - Python 3 - FileNotFoundError: [Errno 2] No such file or directory 错误:FileNotFoundError:[Errno 2]没有这样的文件或目录: - Error: FileNotFoundError: [Errno 2] No such file or directory:
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM