1

在我的代码中,我创建了一个随机数的文本文件。但我想知道是否可以生成多个文件,每次在 for 循环中使用不同范围的随机数。

我对如何实现这一点有一个想法,但我不确定如何调用我每次 testn 制作的文件,其中 n 是 n 的当前值。所以我会有文件:test1、test2 等等。

到目前为止,我的实现是:

numberOfFiles = 5 #set this to the number of files you want to make

for n in range(numberOfFiles):
    newFile = open('testn.txt', 'w') #if possible I want to create a file each time and call it testn, where n is the current value of n.

    x = []

    for i in range(10): #number of lines in each file
        x.append(random.randint(0,60 + (n * 10))

    for val in range(len(x)):
        newFile.write(str(x[val]) + "\n")

    newFile.close()
4

3 回答 3

4

newFile = open('test' + str(n) + '.txt', 'w')

或在 python3.6+ 中:

newfile = open(f'test{n}.txt','w')

于 2020-03-27T14:46:51.063 回答
2

这应该有效:

filename = "test" + str(n) + ".txt"
newFile = open(filename, 'w')
于 2020-03-27T14:47:15.807 回答
0

此代码将为您工作,它将创建 5 个文本文件,每个文件包含您在代码中定义的范围之间的 10 个随机数:

import random
numberOfFiles = 5
for n in range(numberOfFiles):
    filename = "test" + str(n) + ".txt"
    newFile = open(filename, 'w')
    x = []
    for i in range(10): #number of lines in each file
        x.append(random.randint(0,60 + (n * 10)))

    for val in range(len(x)):
        newFile.write(str(x[val]) + "\n")
    newFile.close()
于 2020-03-27T14:58:28.110 回答