簡體   English   中英

返回文件的文件路徑,而不是當前目錄

[英]Return the file path of the file, not the current directory

我有一個 Python/Sikuli 腳本,我需要將文件的位置存儲在一個變量中。

我的 IDE 位於一個位置,文件存儲在不同的目錄中。
IDE: C:\\Sikuli\\runIDE.cmd
文件:C:\\Script\\Files\\HelloWorld2.sikuli\\HelloWorld.py

現在我使用os.getcwd()來獲取 IDE 的位置。
但是如何返回文件“HelloWorld.py”的完整目錄路徑?

我還使用了os.path.abspath("HelloWorld2.py")os.path.dirname(os.path.realpath('HelloWorld2.py'))
但這也不起作用。
誰能幫我這個?

在常規 Python 中,使用__file__返回包含執行文件的目錄的完整路徑:

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

但是,在 Sikuli 中, __file__引用是未定義的:

from sikuli import *
import os

print( os.path.dirname( os.path.abspath( __file__ ) ) )

在 Sikuli v2.0.4 中運行時,我們看到__file__不受支持

[error] script [ test2 ] stopped with error in line 6
[error] NameError ( name '__file__' is not defined )
[error] --- Traceback --- error source first
line: module ( function ) statement 
6: main (  <module> )     print( os.path.dirname( os.path.abspath(__file__) ) )
[error] --- Traceback --- end --------------

相反,使用getBundle() ,例如:

from sikuli import *
import os

print( os.path.dirname( getBundlePath() ) )

Sikuli 似乎對__file__有一些問題
Sikuli 和 Python 的作用是:

os.path.dirname(getBundlePath()) 

編輯以下問題:
要獲取目錄中文件的名稱,您可以執行以下操作:

path = os.path.dirname(getBundlePath()) 
directory = os.listdir(path) 
for file in directory: 
    print(file)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM