如何在Pycharm中打开文件

时间:2016-09-04 09:16:03

标签: python-3.x pycharm

从标题中可以看出我在pycharm中打开文件时遇到了困难。每次我尝试打开文件时都会说:“Errno2:没有这样的文件或目录”

我已将该文件放在my pycharm项目目录中。

以下是截图:  https://gyazo.com/f9c12e266a4608ed8da3ccf9c6f9dbe3

这是我用来打开文件的代码(我将文件重命名为“filef”):

myfile = open("filef.txt", "r")

2 个答案:

答案 0 :(得分:0)

首先,检查您当前的工作目录:

import os
print os.path.abspath(os.curdir)

如果它不是基础项目目录的路径,则执行:

os.chdir('/path/baseproject/directory/or/where/fileislocated')

答案 1 :(得分:0)

@Dani jel 以下解决方案适合我。最简单的方法是使用绝对文件路径,你必须使用原始字符串作为文件路径,在字符串前面使用r或使用双斜杠或正斜杠。

import os
print(os.path.abspath(os.curdir)) # it´s different than file path, so I used the absolute file path in method open

myfile = open(r"C:\Users\Ghost\Downloads\special.txt", "r")
# or relative file path
# myfile = open(r".\Downloads\special.txt", "r")
print(myfile.read())
HELLO WORLD! # it´s from file