Python中找不到文件错误

时间:2013-07-15 16:13:51

标签: 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

7 个答案:

答案 0 :(得分:5)

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

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

$ python script.py

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

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

答案 1 :(得分:2)

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

答案 2 :(得分:2)

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

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库的一部分。

答案 3 :(得分:1)

很难在评论中提供代码示例。

要读取文件中的单词,您可以读取文件的内容,它会为您提供一个字符串 - 这是您以前使用read()方法执行的操作 - 然后使用split()来获取个别的话。 拆分在提供的分隔符上或在默认情况下在空白处分解String。例如,

"the quick brown fox".split()

生成

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

同样,

fileScan.read().split()

将为您提供一系列字符串。 希望有所帮助!

答案 4 :(得分:1)

您可能需要通过以下方式更改路径:

import os
path=os.chdir(str('Here should be the path to your file')) #This command changes directory

这至少对我有用!希望它也适用于您!

答案 5 :(得分:0)

如上所述,问题在于指定文件的路径。 OS X中的默认路径是您的主目录(/ Users / macbook在终端中用〜表示...您可以使用“系统偏好设置”>“用户和组”中的高级选项更改或重命名主目录)。

或者您可以使用文件名指定从驱动器到文件的路径:

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

您还可以捕获“找不到文件”错误并使用try给出另一个响应:

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

答案 6 :(得分:0)

我犯的错误是 我的代码:

x = open('python.txt')

print(x)

但是问题出在文件目录中,我将其另存为python.txt而不是python。

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

这就是它给出错误的原因。

命名不带.txt的文件,它将运行。