简体   繁体   English

Python os.listdir()表现异常,需要一些解释

[英]Python os.listdir() behaving strangely, need some explanation

I am using python, with Anaconda on PyCharm IDE (windows 10), and using virtual environment. 我在PyCharm IDE(Windows 10)上将蟒蛇与Anaconda配合使用,并使用了虚拟环境。 This is my code in question, 这是我有问题的代码,

print('# File...')
print(os.listdir("../MyData/Data/"))

When I run the code in console (right-click and then "Execute Section in Console") it works perfectly. 当我在控制台中运行代码时(右键单击“控制台中的执行部分”),它可以正常运行。 However, as I run the entire code (from the green button) it says, FileNotFoundError: [WinError 3] The system cannot find the path specified: '../MyData/Data/' 但是,当我运行整个代码(通过绿色按钮)时,它说FileNotFoundError:[WinError 3]系统找不到指定的路径:'../MyData/Data/'

Can someone please explain why is it happening, and a possible direction? 有人可以解释为什么会这样吗,以及可能的方向吗? Thank you. 谢谢。

Be carefull, Windows usually have "\\" in the address. 请注意,Windows通常在地址中带有"\\" This is very simple but could be a big problem. 这很简单,但可能是个大问题。 Since "\\" is used as a escape, you will have to use "\\\\" . 由于将"\\"用作转义符,因此必须使用"\\\\" Try this test and see it the address is correct: 试试这个测试,看看它的地址是否正确:

import os
print(os.getcwd())

It will print your current work directory 它将打印您当前的工作目录

您应使用完整路径,如下所示:

os.listdir ("C:\Users\YourUsername\Full\Path")

All programs have a working directory decided by whatever code started it. 所有程序都有一个工作目录,该目录取决于启动它的任何代码。 When you right click and run in console, the console, as part of its initialization process, specifically sets current working directory to your home directory. 右键单击并在控制台中运行时,作为其初始化过程的一部分,控制台会专门将当前工作目录设置为您的主目录。 When you run in the gui what happens depends on the window manager that starts the program. 在gui中运行时,发生的情况取决于启动程序的窗口管理器。 I think Microsoft Windows likes to set CWD to the directory of the executable, but I'm not sure. 我认为Microsoft Windows喜欢将CWD设置为可执行文件的目录,但是我不确定。

The way to fix it is to manually set the current directory when your program starts. 解决该问题的方法是在程序启动时手动设置当前目录。

import os
os.chdir(os.path.expanduser('~'))

You can do this in the gui and console cases. 您可以在gui和控制台案例中执行此操作。 After this code runs, relative paths will be relative to your home directory. 此代码运行后,相对路径将相对于您的主目录。

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

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