![](/img/trans.png)
[英]How to create multiple files with different names and write to them in Python
[英]How to create and write to multiple files in Python?
我在Python中有一個for循環,在每次迭代中,我都希望將結果寫到一個新的文本文件中。
import numpy as np
n = 5
g = my_func()
for i in range(n):
""" I wan to have test0.txt for i = 0
test1.txt for i = 1 and so on ...
"""
f = open('test.txt','ab')
np.savetxt(f, g, fmt='%.0f', newline=" ")
f.close()
這可能嗎?
我的n
真實值為1000
您可以使用format
為文件名創建字符串
f = open('test{}.txt'.format(i), 'ab')
因此您的代碼可以修改為
import numpy as np
n = 5
g = my_func()
for i in range(n):
with open('test{}.txt'.format(i), 'ab') as f:
np.savetxt(f, g, fmt='%.0f', newline=" ")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.