0

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"

I already put the file in the directory my pycharm project is.

Here is a screenshot: https://gyazo.com/f9c12e266a4608ed8da3ccf9c6f9dbe3

Here's the code I use to open the file (I renamed the file to "filef"):

myfile = open("filef.txt", "r")
Dani jel
  • 11
  • 1
  • 6

2 Answers2

1

First, check your current working directory:

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

If it is not the path of your base project directory, then do:

os.chdir('/path/baseproject/directory/or/where/fileislocated')
Devi Prasad Khatua
  • 1,185
  • 3
  • 11
  • 23
  • Now I get no error and the code runs but the file doesn't seem to open anywhere. I dont know if this has to be like this or did I do something wrong. – Dani jel Sep 05 '16 at 09:17
  • @Danijel Also it's possible to specify working directory of running script in `Run Configuration` setting. For more details see http://stackoverflow.com/a/37655658/2235698 – user2235698 Sep 05 '16 at 09:58
  • @Danijel what do you mean by "the file doesn't seem to open anywhere" - Be specific! – Devi Prasad Khatua Sep 06 '16 at 11:58
  • @wolframalpha I mean i don' see the text from the file or the file anywhere when i execute the code. – Dani jel Sep 06 '16 at 14:20
  • @Danijel if the file contains special characters, try opening the file in Unicode - by `import codecs; f = codecs.open("filef.txt", "r", "utf-8")` and then print ! – Devi Prasad Khatua Sep 06 '16 at 14:47
  • @wolframalpha This doesn't work either, I still don't see the text from it anywhere, The text is just one word. By the way UTF - 8 was automatically put as default setting in my pycharm – Dani jel Sep 07 '16 at 09:39
0

@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
Ghost
  • 309
  • 1
  • 4
  • 10