[英]When importing python script from another folder how to save output in the library/sub-folder
我正在運行此腳本( parent.py
)
import sys
sys.path.append('/python/loanrates/test')
import test2
test2
從此目錄:
D:\python\loanrates\Parent
哪個打開此腳本( test.py
)
import json
data = 'ello world'
with open( 'it_worked.json', 'w') as f:
json.dump(data, f)
從這個方向
D:\python\loanrates\test
當我運行隨后運行test.py
parent.py
,我希望json.dump保存在D:\\python\\loanrates\\test' currently it saves in
D:\\ python \\ loanrates \\ Parent`中
編輯:我進行了以下編輯:
現在是子文件:
import json
def main():
data = 'ello world'
print data
with open( 'D:/python/loanrates/test/it_worked.json', 'w') as f:
json.dump(data, f)
if __name__ == '__main__':
main()
這是我的父母:
import sys
import thread
sys.path.append('/python/loanrates/test')
import test2
thread.start_new_thread(test2.main())
我收到此錯誤:
TypeError: start_new_thread expected at least 2 arguments, got 1
我需要輸入的第二個參數是什么?
import os
local_path = os.path.dirname(__file__)
with open(local_path + '/output.txt', 'w') as fh:
fh.write('here i am')
import importlib.machinery, imp
namespace = 'testing'
fullPath = r'C:\Users\OpenWindows\Desktop\script\test\testing.py'
loader = importlib.machinery.SourceFileLoader(namespace, fullPath)
testing = loader.load_module(namespace)
# Code should have been executed in testing.py now.
這是一個選項,因為您需要相對路徑,所以可以從本地__file__
變量獲取路徑,因為它包含模塊路徑的路徑而不是執行路徑。
還有一個使用import ()的選項,該選項可以傳遞全局變量,您可以在其中修改更改的全局變量來滿足您的需求。
我想到了:
我將test.py
的代碼更改為
import time
import json
data = 'ello world'
with open( 'D:/python/loanrates/test/it_worked.json', 'w') as f:
json.dump(data, f)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.