我有一個目錄存儲一些python源文件(a_dir/*.py
)。 每個* .py文件都有a_var
對象。動態讀取來自多個源文件的變量
我想要在a_dir
的同一目錄下創建一個腳本來構建一個包含所有a_var
值的列表a_var_list
。
我雖然要循環通過a_dir
中的python源文件,臨時加載每個模塊並讀取對象a_var
來構造a_var值的python列表。
我有一個目錄存儲一些python源文件(a_dir/*.py
)。 每個* .py文件都有a_var
對象。動態讀取來自多個源文件的變量
我想要在a_dir
的同一目錄下創建一個腳本來構建一個包含所有a_var
值的列表a_var_list
。
我雖然要循環通過a_dir
中的python源文件,臨時加載每個模塊並讀取對象a_var
來構造a_var值的python列表。
如果您不想進行文本解析,您可以嘗試導入所有文件並訪問a_var變量。要做到這一點,你應該使用「著名的」
if __name__ == '__main__':
<code>
如果您沒有使用該方法,以最快的方式仍然是文件的解析已經寫侑文件。我會使用類似以下內容:
import glob
import re
results = []
avar_regex = re.compile(r'\s*a_var\s*=\s*(.*)\s*')
# to define the regex it would be important to know a little bit
#+more about the variable you are looking for.
# glob can be used to create a list with all the file names
for f in glob.glob('a_dir/*.py'):
with open(f) as fc:
while l in fc:
match = avar_regex.match(l)
if match:
results.append(match.group(1))
break
也許是這樣嗎?
進口
import os
import sys
sys.path.append("a_dir")
a_list = []
for directory in os.walk("a_dir"): #should only iterate once
for file in directory[2]:
if file.split(".")[-1] == "py":
module = __import__(".".join(file.split(".")[:-1]))
if "a_var" in dir(module):
a_list.append(module.a_var)
這將重新執行所有的python文件,如果他們做得不好(正如我在我的回答中所提到的那樣) –
我得到了AttributeError:'module'對象沒有屬性'a_var' –
啊,這是假定每個目錄中的模塊定義了a_var。我會編輯解決方案來解決這個問題 – Quack
你嘗試過什麼樣的方法?嘗試[glob](https://docs.python.org/3/library/glob.html)模塊。 –
請不要說,我會回答我的問題。 –