Python中找不到文件错误

Ash*_*ngs 6 python

我确信之前已经回答了,但我找不到任何可以帮助我...

我正在尝试编写一个简单的程序来读取文件并搜索一个单词,然后打印该文件中找到该单词的次数.好吧,每当我输入"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'
Run Code Online (Sandbox Code Playgroud)

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

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

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
Run Code Online (Sandbox Code Playgroud)

Jan*_*cke 6

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

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

$ python script.py
Run Code Online (Sandbox Code Playgroud)

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

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


use*_*863 5

一个好的开始是验证输入。换句话说,您可以确保用户确实为真实存在的文件键入了正确的路径,如下所示:

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.")
Run Code Online (Sandbox Code Playgroud)

这是在内置模块os 的帮助下完成的,它是标准 Python 库的一部分。

  • FWIW,通常使用 try-except 是更好的做法,即 `try: open(fileName); except FileNotFoundError: print('哎呀!没有这样的文件!') ...` (2认同)