0

I'm trying to open a file that does not exist in my current directory. This file is named testFile.py existing in the data folder in my current directory. I tried sys.path.append("./data") and then wanted to show the file with this command open("testFile.py") but it gives this error:

open("testFile.py") FileNotFoundError:

[Errno 2] No such file or directory: 'testFile.py'

When printing the command os.getcwd() gives the previous current directory. So any thoughts on this?

Community
  • 1
  • 1
ezzeddin
  • 499
  • 2
  • 5
  • 25
  • 1
    Possible duplicate of [How to set the current working directory?](https://stackoverflow.com/questions/1810743/how-to-set-the-current-working-directory) – DavidG Apr 13 '18 at 15:12
  • Actually I'm asking about concatenating a directory to my current directory. – ezzeddin Apr 13 '18 at 15:17

1 Answers1

0

Have you tried...

open("data/testFile.py")

Or if you need to import...

import sys
import os

sys.path.append(os.getcwd()+os.sep+"data")
import testFile

Not sure if this is what you mean, but if you want to list the files in the subdirectory...

import os
path = os.getcwd()+os.sep+"data"
files = os.listdir(path)
print(files)

Or you can change the current working directory with...

...
os.chdir(path)
Adil
  • 127
  • 1
  • 8
  • For the first case, it gives the same error that no such directory or file exists. For the second one, it doesn't give any error but also doesn't show the file and when I print the directory it gives the previous directory (i.e. not inside the `data` folder. – ezzeddin Apr 13 '18 at 15:42
  • I need to import it as a code. I found the file when I did the last part `print(files)` but when I used `open(testFile.py)` it says no file or directory. I think my problem with `open` command. Is there is something alternative? – ezzeddin Apr 13 '18 at 16:27