简体   繁体   中英

How can I set different directory to the current directory in python?

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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