3 回答

TA貢獻1842條經(jīng)驗 獲得超13個贊
您可以使用三引號來簡化事情。
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條經(jīng)驗 獲得超3個贊
new_file = "print('line1')\n" \
"print('line2')\n" \
"print('line3')"
f = open('new_python.py', 'w')
print(new_file, file=f)

TA貢獻1828條經(jīng)驗 獲得超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)
添加回答
舉報