简体   繁体   English

我无法打开Python文件:(

[英]I'm having trouble opening a Python file :(

I saved a file as DictionaryE.txt in a Modules folder I created within Python. 我在Python中创建的Modules文件夹中将文件另存为DictionaryE.txt。 Then I type: 然后我输入:

fh = open("DictionaryE.txt")

I get this error message: 我收到此错误消息:

Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    fh = open("DictionaryE.txt")
IOError: [Errno 2] No such file or directory: 'DictionaryE.txt'

What am I doing wrong? 我究竟做错了什么? Could someone please describe a specific, detailed step-by-step instruction on what to do? 有人可以描述具体的详细分步说明,该怎么做吗? Thanks. 谢谢。

As other answers suggested, you need to specify the file's path, not just the name. 正如其他答案所建议的那样,您需要指定文件的路径,而不仅仅是名称。

For example, if you know the file is in C:\\Blah\\Modules , use 例如,如果您知道文件在C:\\Blah\\Modules ,请使用

fh = open('c:/Blah/Modules/DictionaryE.txt')

Note that I've turned the slashes "the right way up" (Unix-style;-) rather than "the Windows way". 请注意,我已将斜线“朝正确的方向”(Unix样式;-)而不是“ Windows方式”。 That's optional, but Python (and actually the underlying C runtime library) are perfectly happy with it, and it saves you trouble on many occasions (since \\ , in Python string literals just as in C ones, is an "escape marker", once in a while, if you use it, the string value you've actually entered is not the one you think -- with '/' instead, zero problems). 这是可选的,但是Python(实际上是底层的C运行时库)对此非常满意, 并且它在很多情况下都可以避免麻烦(因为\\ ,就像在C语言中一样,在Python字符串常量中是\\在一段时间内,如果您使用它,则实际上输入的字符串值不是您认为的值-带有'/'的零错误)。

Use the full path to the file? 使用文件的完整路径? You are trying to open the file in the current working directory. 您正在尝试在当前工作目录中打开文件。

probably something like: 大概是这样的:

import os
dict_file = open(os.path.join(os.path.dirname(__file__), 'Modules', 'DictionaryE.txt'))

It's hard to know without knowing your project structure and the context of your code. 不知道您的项目结构和代码上下文就很难知道。 Fwiw, when you just "open" a file, it will be looking in whatever directory you're running the python program in, and __file__ is the full path to ... the python file. 首先,当您“打开”文件时,它将在您正在其中运行python程序的任何目录中查找,并且__file__是... python文件的完整路径。

To complement Alex's answer, you can be more specific and explicit with what you want to do with DictionaryE.txt . 为了补充Alex的答案,您可以使用DictionaryE.txt进行更具体,更明确的说明。 The basics: 基础:

READ (this is default): 读取(这是默认设置):

fh = open("C:/path/to/DictionaryE.txt", "r")

WRITE: 写:

fh = open("C:/path/to/DictionaryE.txt", "w")

APPEND: 附加:

fh = open("C:/path/to/DictionaryE.txt", "a")

More info can be found here: Built-in Functions - open() 可以在这里找到更多信息: 内置函数open()

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

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