简体   繁体   English

无法获取__file__ Python的实际目录

[英]Unable to obtain actual directory for __file__ Python

I've been trying to get the location of an open .py file (using Spyder) that will be used to link various files and use the __file__ name so that any machine can run from its current directory. 我一直在尝试获取打开的.py文件(使用Spyder)的位置,该文​​件将用于链接各种文件并使用__file__名称,以便任何计算机都可以从其当前目录运行。

The problem is that when I try: 问题是当我尝试:

location = os.path.abspath(os.path.dirname(__file__))

It gives me the error: 它给了我错误:

NameError: name '__file__' is not defined

I bypassed this by calling on the file as a string rather than the name file variable using: 我通过使用字符串而不是名称文件变量调用文件来绕过此操作:

location = os.path.abspath(os.path.dirname('__file__'))

This worked for getting me the parent directory of the file but not the actual folder that the file was in: 这可以使我获得文件的父目录,而不是文件所在的实际文件夹:

location = 'C:\Users\......\Scripts'

When really the location is in: 实际位置在:

location = 'C:\Users\......\Scripts\ISO'

I've tried various combinations of abspath and dirname and realpath to get the true directory that the file is in but I cannot get it. 我已经尝试了abspathdirname以及realpath各种组合来获取文件所在的真实目录,但是我无法获取它。

What am I doing incorrectly? 我做错了什么?

Because I was running the script inside the Spyder shell it did not output the proper working directory because the working directory settings were somehow misaligned with the file's path. 因为我在Spyder外壳中运行脚本,所以它没有输出正确的工作目录,因为工作目录设置与文件的路径不匹配。

This can be solved by Run -> Configuration per file -> The directory of the file being executed 可以通过Run -> Configuration per file -> The directory of the file being executed来解决

But the more effective way of running the script using __file__ is to run the script from the python3.X.exe file in the directory which the script is located. 但是,使用__file__运行脚本的更有效方法是从脚本python3.X.exe目录中的python3.X.exe文件运行脚本。

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

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