为什么我会收到 FileNotFoundError 错误? [英] Why am I getting a FileNotFoundError?

查看:45
本文介绍了为什么我会收到 FileNotFoundError 错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个简单的程序来读取文件并搜索一个单词,然后打印在文件中找到该单词的次数.每次我输入test.rtf"(这是我的文档的名称)我收到此错误:

I'm trying to write a simple program to read a file and search for a word then print how many times that word is found in the file. Every time I type in "test.rtf" (which is the name of my document) I get this error:

Traceback (most recent call last):
  File "/Users/AshleyStallings/Documents/School Work/Computer Programming/Side Projects/How many? (Python).py", line 9, in <module>
    fileScan= open(fileName, 'r')  #Opens file
FileNotFoundError: [Errno 2] No such file or directory: 'test.rtf'

上学期上课时,我记得我的教授说你必须把文件保存在一个特定的地方?我不确定他是否真的这么说,但如果有帮助的话,我正在运行 Apple OSx.

In class last semester, I remember my professor saying you have to save the file in a specific place? I'm not sure if he really said that though, but I'm running apple OSx if that helps.

这是我的代码的重要部分:

Here's the important part of my code:

fileName= input("Please enter the name of the file you'd like to use.")
fileScan= open(fileName, 'r')  #Opens file

推荐答案

如果用户没有将完整路径传递给文件(在 Unix 类型系统上,这意味着路径以斜杠开头),路径将被相对解释到当前工作目录.当前工作目录通常是您启动程序的目录.在您的情况下,文件 test.rtf 必须在您执行程序的同一目录中.

If the user does not pass the full path to the file (on Unix type systems this means a path that starts with a slash), the path is interpreted relatively to the current working directory. The current working directory usually is the directory in which you started the program. In your case, the file test.rtf must be in the same directory in which you execute the program.

您显然是在 Mac OS 下用 Python 执行编程任务.在那里,我建议在终端中工作(在命令行上),即启动终端,cd 到输入文件所在的目录,然后使用命令在那里启动 Python 脚本

You are obviously performing programming tasks in Python under Mac OS. There, I recommend to work in the terminal (on the command line), i.e. start the terminal, cd to the directory where your input file is located and start the Python script there using the command

$ python script.py

为了使这个工作,包含 python 可执行文件的目录必须在 PATH 中,一个所谓的环境变量,其中包含在您输入命令时自动用于搜索可执行文件的目录.您应该利用它,因为它极大地简化了日常工作.这样,您只需 cd 到包含 Python 脚本文件的目录并运行它.

In order to make this work, the directory containing the python executable must be in the PATH, a so-called environment variable that contains directories that are automatically used for searching executables when you enter a command. You should make use of this, because it simplifies daily work greatly. That way, you can simply cd to the directory containing your Python script file and run it.

在任何情况下,如果您的 Python 脚本文件和您的数据输入文件不在同一目录中,您总是必须指定它们之间的相对路径,或者您必须为其中之一指定绝对路径.

In any case, if your Python script file and your data input file are not in the same directory, you always have to specify either a relative path between them or you have to use an absolute path for one of them.

这篇关于为什么我会收到 FileNotFoundError 错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆