簡體   English   中英

如何在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM