3 回答

TA貢獻(xiàn)1842條經(jīng)驗(yàn) 獲得超13個(gè)贊
您可以使用三引號(hào)來簡(jiǎn)化事情。
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)
請(qǐng)參閱文檔。大約在頁(yè)面下方的三分之一處。

TA貢獻(xiàn)1803條經(jīng)驗(yàn) 獲得超3個(gè)贊
new_file = "print('line1')\n" \
"print('line2')\n" \
"print('line3')"
f = open('new_python.py', 'w')
print(new_file, file=f)

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超13個(gè)贊
如果你想保存到文件中,最終它必須是一個(gè)字符串。
該文件的兩個(gè)變體看起來非常相似,因此不要將其寫入兩次:
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)
添加回答
舉報(bào)