在Python中找不到文件错误

2024-04-18 19:13:17 发布

您现在位置: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'

在上学期的课上,我好像记得我的教授说你必须把文件保存在一个特定的地方?我不确定他是否真的这么说,但如果这有帮助的话,我正在运行苹果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

Tags: or文件thetonoinforinput
3条回答

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

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.")

这需要内置模块os的一些帮助,该模块是标准Python库的一部分。

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

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

$ python script.py

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

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

test.rtf是否位于运行此命令时所在的同一目录中?

如果没有,则需要提供该文件的完整路径。

假设它位于

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

如果那样的话,你可以进入

data/test.rtf

作为您的文件名

或者它可能在

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

如果那样的话,你可以进入

../some_other_folder/test.rtf

相关问题 更多 >