如何在 Pycharm 中打开文件 [英] How to open files in Pycharm
问题描述
正如您从标题中看到的,我在 pycharm 中打开文件时遇到了困难.每次我尝试打开一个文件时,它都会说:Errno2:没有这样的文件或目录"
as you can see from the title I am having difficulties opening files in pycharm. Every time I try to open a file it says: "Errno2: no such file or directory"
我已经把文件放在了我的pycharm项目所在的目录中.
I already put the file in the directory my pycharm project is.
截图如下:https://gyazo.com/f9c12e266a4608ed8da3ccf9c6f9dbe3
这是我用来打开文件的代码(我将文件重命名为filef"):
Here's the code I use to open the file (I renamed the file to "filef"):
myfile = open("filef.txt", "r")
推荐答案
@Dani jel下面的解决方案对我有用.最简单的方法是使用绝对文件路径,您必须使用原始字符串作为文件路径,字符串前面有 r 或使用双斜杠或正斜杠.
@Dani jel Solution below works for me. The easiest way how to do it is to use absolute file path and you have to use raw string as a file path with r in front of string or use double slashes or forward slashes.
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
这篇关于如何在 Pycharm 中打开文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!