簡體   English   中英

從另一個文件夾導入python腳本時,如何將輸出保存在庫/子文件夾中

[英]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

我需要輸入的第二個參數是什么?

../script/test/testing.py

import os
local_path = os.path.dirname(__file__)

with open(local_path + '/output.txt', 'w') as fh:
    fh.write('here i am')

../script/parent/parent.py

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.

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