如何编写文件然后导入它

时间:2018-01-14 16:58:04

标签: python python-3.x python-import

我需要将一些变量写入文件然后导入它。但是,每当我尝试运行它时,控制台都会说该变量不存在。

file_writer.py

target = open('save.py', 'w')
target.write('x = 2')
from save import *
print(x)

save.py

x = 2
在运行save.py之前,

file_writer.py为空。

2 个答案:

答案 0 :(得分:0)

您可以选择尝试以下代码段:

with open('vars.txt', 'w') as file_:
    file_.write('x = 2')

with open('vars.txt', 'r') as file_:
    exec(file_.read())

print(x)
# 2

答案 1 :(得分:0)

例如,您可以将数据保存在结构化JSON文件中:

import json

filename = 'data.json'

data = {
    'x': 1,
    'y': 2
}

with open(filename, 'w+') as f:
    json.dump(data, f)

try:
    with open(filename, 'r') as f:
        loaded_data = json.load(f)
except IOError:
    print('File not found.')

# Print all data:
print(json.dumps(loaded_data, indent=2, sort_keys=True))
# {
#     "x": 1,
#     "y": 2
# }

# Print selected elements:
print(loaded_data.get('x'))
print(loaded_data.get('y'))
print(loaded_data.get('z', 3))  # with a default value