3 回答
TA贡献1842条经验 获得超12个赞
您可以使用三引号来简化事情。
if x==0:
path = "test.py"
string = """\
import requests, json
URL = "https://.../login"
headers = {"Content-Type":"application/json"}
params = {
"userName":"xx",
"password":"yy"
}
resp = requests.post(URL, headers = headers, data=json.dumps(params))
if resp.status_code != 200:
print('fail')
else:
print('Success')
"""
else:
path = "other.py"
string = """\
import requests, json
URL = "https://.../login"
headers = {"Content-Type":"application/json"}
params = {
"userName":"RR",
"password":"TT"
}
resp = requests.post(URL, headers = headers, data=json.dumps(params))
if resp.status_code != 200:
print('fail')
else:
print('Success')
"""
with open(path, 'w') as f:
f.write(string)
请参阅文档。大约在页面下方的三分之一处。
TA贡献1803条经验 获得超3个赞
new_file = "print('line1')\n" \
"print('line2')\n" \
"print('line3')"
f = open('new_python.py', 'w')
print(new_file, file=f)
TA贡献1828条经验 获得超13个赞
如果你想保存到文件中,最终它必须是一个字符串。
该文件的两个变体看起来非常相似,因此不要将其写入两次:
template ='''
URL = "https://.../login"
headers = {"Content-Type":"application/json"}
params = {
"userName":"%s",
"password":"%s"
}
resp = requests.post(URL, headers = headers, data=json.dumps(params))
if resp.status_code != 200:
print('fail')
else:
print('Success')
'''
if x == 0:
content = template % ("xx", "yy")
else:
content = tempalte % ("RR", "TT")
with open("test.py", "w") as f:
f.write(content)
添加回答
举报