简体   繁体   English

为什么我会收到 FileNotFoundError?

[英]Why am I getting a FileNotFoundError?

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:每次我输入“test.rtf”(这是我的文档的名称)时,我都会收到以下错误:

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'

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.我不确定他是否真的这么说,但如果有帮助,我正在运行苹果 OSx。

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

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.如果用户没有传递文件的完整路径(在 Unix 类型系统上,这意味着以斜杠开头的路径),则相对于当前工作目录解释路径。 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.在您的情况下,文件test.rtf必须位于您执行程序的同一目录中。

You are obviously performing programming tasks in Python under Mac OS.您显然是在 Mac OS 下使用 Python 执行编程任务。 There, I recommend to work in the terminal (on the command line), ie start the terminal, cd to the directory where your input file is located and start the Python script there using the command在那里,我建议在终端中工作(在命令行上),即启动终端, cd到您的输入文件所在的目录,然后使用命令在那里启动 Python 脚本

$ python script.py

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.为了完成这项工作,包含 python 可执行文件的目录必须位于 PATH 中,这是一个所谓的环境变量,其中包含在您输入命令时自动用于搜索可执行文件的目录。 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.这样,您可以简单地cd到包含 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.在任何情况下,如果您的 Python 脚本文件和数据输入文件不在同一个目录中,您必须始终指定它们之间的相对路径,或者必须为其中之一指定绝对路径。

Is test.rtf located in the same directory you're in when you run this? test.rtf是否位于您运行此程序时所在的同一目录中?

If not, you'll need to provide the full path to that file.如果没有,您需要提供该文件的完整路径。

Suppose it's located in假设它位于

/Users/AshleyStallings/Documents/School Work/Computer Programming/Side Projects/data

In that case you'd enter在这种情况下,您将输入

data/test.rtf

as your file name作为你的文件名

Or it could be in或者它可能在

/Users/AshleyStallings/Documents/School Work/Computer Programming/some_other_folder

In that case you'd enter在这种情况下,您将输入

../some_other_folder/test.rtf

A good start would be validating the input.一个好的开始是验证输入。 In other words, you can make sure that the user has indeed typed a correct path for a real existing file, like this:换句话说,您可以确保用户确实为真实的现有文件键入了正确的路径,如下所示:

import os
fileName = input("Please enter the name of the file you'd like to use.")
while not os.path.isfile(fileName):
    fileName = input("Whoops! No such file! Please enter the name of the file you'd like to use.")

This is with a little help from the built in module os , That is a part of the Standard Python Library.这得益于内置模块os的一点帮助,它是标准 Python 库的一部分。

As noted above the problem is in specifying the path to your file.如上所述,问题在于指定文件的路径。 The default path in OS X is your home directory (/Users/macbook represented by ~ in terminal ...you can change or rename the home directory with the advanced options in System Preferences > Users & Groups). OS X 中的默认路径是您的主目录(/Users/macbook 在终端中由 ~ 表示...您可以使用系统偏好设置 > 用户和组中的高级选项更改或重命名主目录)。

Or you can specify the path from the drive to your file in the filename:或者您可以在文件名中指定从驱动器到文件的路径:

path = "/Users/macbook/Documents/MyPython/"
myFile = path + fileName

You can also catch the File Not Found Error and give another response using try:您还可以捕获 File Not Found 错误并使用 try 给出另一个响应:

try:
    with open(filename) as f:
        sequences = pick_lines(f)
except FileNotFoundError:
    print("File not found. Check the path variable and filename")
    exit()

You might need to change your path by:您可能需要通过以下方式更改路径:

import os
path=os.chdir(str('Here_should_be_the_path_to_your_file')) #This command changes directory

This is what worked for me at least!这至少对我有用! Hope it works for you too!希望它也适合你!

Difficult to give code examples in the comments.很难在评论中给出代码示例。

To read the words in the file, you can read the contents of the file, which gets you a string - this is what you were doing before, with the read() method - and then use split() to get the individual words.要读取文件中的单词,您可以读取文件的内容,这会为您获取一个字符串 - 这是您之前使用 read() 方法所做的 - 然后使用 split() 获取各个单词。 Split breaks up a String on the delimiter provided, or on whitespace by default. Split 在提供的分隔符上或默认情况下在空格上分解字符串。 For example,例如,

"the quick brown fox".split()

produces生产

['the', 'quick', 'brown', 'fox']

Similarly,相似地,

fileScan.read().split()

will give you an array of Strings.会给你一个字符串数组。 Hope that helps!希望有帮助!

The mistake I did was my code :我犯的错误是我的代码:

x = open('python.txt') x = 打开('python.txt')

print(x)打印(x)

But the problem was in file directory ,I saved it as python.txt instead of just python .但问题出在文件目录中,我将其保存为 python.txt 而不仅仅是 python 。

So my file path was ->C:\Users\noob\Desktop\Python\Course 2\python.txt.txt所以我的文件路径是 ->C:\Users\noob\Desktop\Python\Course 2\python.txt.txt

That is why it was giving a error.这就是它给出错误的原因。

Name your file without .txt it will run.将您的文件命名为不带 .txt 的文件,它将运行。

First check what's your file format(eg: .txt, .json, .csv etc ),首先检查您的文件格式是什么(例如:.txt、.json、.csv 等),

If your file present in PWD , then just give the name of the file along with the file format inside either single('')or double("") quote and the appropriate operation mode as your requirement如果您的文件存在于 PWD 中,则只需在单('')或双(“”)引号内提供文件名以及文件格式,并根据您的要求提供适当的操作模式

eg:例如:

with open('test.txt','r') as f: data=f.readlines() for i in data: print(i) If your file present in other directory, then just give the full path name where is your file is present and file name along with file format of the file inside either single('')or double("") quote and the appropriate operation mode as your requirement. with open('test.txt','r') as f: data=f.readlines() for i in data: print(i)如果您的文件存在于其他目录中,则只需提供完整路径名文件存在,文件名以及文件在单('')或双(“”)引号内的文件格式以及您要求的适当操作模式。

If it showing unicode error just put either r before quote of file path or else put '/' instead of ''如果它显示 unicode 错误,只需将 r 放在文件路径的引号之前,否则将 '/' 而不是 ''

with open(r'C:\Users\soman\Desktop\test.txt','r') as f: data=f.readlines() for i in data: print(i)

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM