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