Python中找不到文件错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17658856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:49:21  来源:igfitidea点击:

File Not Found Error in Python

python

提问by Ashley Elisabeth Stallings

I'm sure this has been answered before, but I couldn't find anything to help me...

我确定之前已经回答过这个问题,但是我找不到任何可以帮助我的东西...

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. Well, 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 seem to 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. Haha

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

Here's my code, and any help is appreciated :) Thanks in advance!

这是我的代码,任何帮助表示赞赏:) 提前致谢!

print ("Hello! Welcome to the 'How many' program.")
fileName= input("Please enter the name of the file you'd like to use.  Make \
sure to include the correct extension!")  #Gets file name

fileScan= open(fileName, 'r')  #Opens file

cont = "Yes"
accumulator = 0

while cont == "Yes":
    word=input("Please enter the word you would like to scan for.") #Asks for word
    capitalized= word.capitalize()  
    lowercase= word.lower()

    print ("\n")
    print ("\n")        #making it pretty
    print ("Searching...")

    for word in fileScan.read():  #checking for word
           accumulator += 1

    print ("The word ", word, "is in the file ", accumlator, "times.")

    cont = input ('Type "Yes" to check for another word or \
"No" to quit.')  #deciding next step
    cont = cont.capitalize()

    if cont != "No" or cont != "Yes":  #checking for valid input
        print ("Invalid input.")
        cont = input ('Type "Yes" to check for another word or \
"No" to quit.')  
    cont = cont.capitalize()

print ("Thanks for using How many!")  #ending

回答by Dr. Jan-Philip Gehrcke

If the user does not pass the full path (On Unix type systems this means the path is starting with a slash) to the file, 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.rtfmust be in the same directory in which you execute the program.

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

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, cdto the directory where your input file is located and start the Python script there using the command

您显然是在 Mac OS 下用 Python 执行编程任务。在那里,我建议在终端中工作(在命令行上),即启动终端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. You should make use of this, because it simplifies daily work greatly. That way, you can simply cdto the directory containing your Python script file and run it.

为了使这个工作,包含 python 可执行文件的目录必须在 PATH 中,一个所谓的环境变量,其中包含在您输入命令时自动用于搜索可执行文件的目录。您应该利用它,因为它极大地简化了日常工作。这样,您可以简单地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 脚本文件和您的数据输入文件不在同一目录中,您总是必须指定它们之间的相对路径,或者您必须为其中之一指定绝对路径。

回答by Jon Kiparsky

Is test.rtflocated 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

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

In that case you'd enter

在那种情况下,你会输入

data/test.rtf

data/test.rtf

as your file name

作为你的文件名

Or it could be in

或者它可能在

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

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

In that case you'd enter

在那种情况下,你会输入

../some_other_folder/test.rtf

../some_other_folder/test.rtf

回答by user1555863

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)) or (not os.path.exists(fileName)):
    fileName = input("Whhoops! 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 库的一部分。

回答by Jon Kiparsky

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. Split breaks up a String on the delimiter provided, or on whitespace by default. For example,

要读取文件中的单词,您可以读取文件的内容,这会为您提供一个字符串——这就是您之前所做的,使用 read() 方法——然后使用 split() 获取单个单词。拆分在提供的分隔符上或默认情况下在空格上拆分字符串。例如,

"the quick brown fox".split()

produces

产生

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

Similarly,

相似地,

fileScan.read().split()

will give you an array of Strings. Hope that helps!

会给你一个字符串数组。希望有帮助!

回答by Spookpadda

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()