San*_*ago 56 python file-io file filenotfoundexception file-not-found
出于某种原因,我的代码无法打开一个简单的文件:
这是代码:
file1 = open('recentlyUpdated.yaml')
Run Code Online (Sandbox Code Playgroud)
错误是:
IOError: [Errno 2] No such file or directory: 'recentlyUpdated.yaml'
Run Code Online (Sandbox Code Playgroud)
open()的完整路径,似乎没有任何工作.Lan*_*aru 62
os.listdir()查看当前工作目录中的文件列表os.getcwd()(如果从IDE启动代码,则可能位于不同的目录中)os.chdir(dir),dir作为文件所在的文件夹,然后打开文件,其名称就像您正在做的那样.open呼叫中文件的绝对路径.dir = r'C:\Python32'
'C:\\User\\Bob\\...''C:/Python32',不需要转义.让我澄清Python如何找到文件:
working directory.您可以通过调用来查看Python的当前工作目录os.getcwd().如果你尝试这样做open('sortedLists.yaml'),Python会看到你传递一个相对路径,所以它将搜索当前工作目录中的文件.调用os.chdir将更改当前工作目录.
示例:假设file.txt找到了C:\Folder.
要打开它,你可以这样做:
os.chdir(r'C:\Folder')
open('file.txt') #relative path, looks inside the current working directory
Run Code Online (Sandbox Code Playgroud)
要么
open(r'C:\Folder\file.txt') #full path
Run Code Online (Sandbox Code Playgroud)
Ara*_*Fey 19
最有可能的问题是您使用相对文件路径打开文件,但当前工作目录未设置为您认为的那样。
相对路径是相对于 python 脚本的位置的,这是一个常见的误解,但这是不正确的。相对文件路径总是相对于当前工作目录,当前工作目录不必是你的python 脚本的位置。
您有三个选择:
使用绝对路径打开文件:
file = open(r'C:\path\to\your\file.yaml')
Run Code Online (Sandbox Code Playgroud)生成相对于您的 python 脚本的文件路径:
from pathlib import Path
script_location = Path(__file__).absolute().parent
file_location = script_location / 'file.yaml'
file = file_location.open()
Run Code Online (Sandbox Code Playgroud)
(另请参阅:如何获取当前正在执行的文件的路径和名称?)
在打开文件之前更改当前工作目录:
import os
os.chdir(r'C:\path\to\your\file')
file = open('file.yaml')
Run Code Online (Sandbox Code Playgroud)其他可能导致“找不到文件”错误的常见错误包括:
在文件路径中意外使用转义序列:
path = 'C:\Users\newton\file.yaml'
# Incorrect! The '\n' in 'Users\newton' is a line break character!
Run Code Online (Sandbox Code Playgroud)
为避免犯此错误,请记住对文件路径使用原始字符串文字:
path = r'C:\Users\newton\file.yaml'
# Correct!
Run Code Online (Sandbox Code Playgroud)
(另请参阅:Python 中的 Windows 路径)
忘记 Windows 不显示文件扩展名:
由于 Windows 不显示已知的文件扩展名,有时当您认为文件file.yaml名为file.yaml.yaml. 仔细检查文件的扩展名。
该文件可能存在但可能具有不同的路径.尝试编写文件的绝对路径.
尝试os.listdir()函数来检查至少python看到的文件.
试试这样:
file1 = open(r'Drive:\Dir\recentlyUpdated.yaml')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
302417 次 |
| 最近记录: |