简体   繁体   English

如何在python中将其他目录设置为当前目录?

[英]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. 该文件名为testFile.py存在于当前目录的data文件夹中。 I tried sys.path.append("./data") and then wanted to show the file with this command open("testFile.py") but it gives this error: 我尝试了sys.path.append("./data") ,然后想使用以下命令open("testFile.py")显示文件,但它给出了此错误:

open("testFile.py") FileNotFoundError: open(“ testFile.py”)FileNotFoundError:

[Errno 2] No such file or directory: 'testFile.py' [Errno 2]没有这样的文件或目录:'testFile.py'

When printing the command os.getcwd() gives the previous current directory. 打印命令时, os.getcwd()给出先前的当前目录。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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