在与 python 脚本相同的目录中将文件用作命令行参数时遇到问题

Having trouble using a file as a command-line argument in the same directory as the python script

我正在尝试编写一个 .py 脚本,它将另一个文件作为命令参数,cmd 参数文件与所述脚本位于同一目录中。

我目前拥有的是:

import sys
java_file = open(sys.argv[1],"r")
<rest of file>

如果我有这样的命令行参数,它就可以正常工作:

python.exe "D:\<user>\<more file directories>\balanced.py" "D:\<user>\<same file directories>\Driver.java"

我想做的是让命令行参数类似于:

python.exe "D:\<user>\<more file directories>\balanced.py" Driver.java

运行 在 Windows 10 命令提示符下使用 Python 3.7.3.

在 Windows 上,sys.argv[0] 应该是您脚本的完整路径,因此您可以使用 os.path.split(sys.argv[0])[0] 获取路径,然后 os.path.join() 加入它

import sys, os
java_file = open(os.path.join(os.path.split(sys.argv[0])[0], sys.argv[1]))