1

In my code I create a text file of random numbers. But I am wondering if it is possible to generate multiple files, each time with different ranges for the random numbers within a for loop.

I have an idea for how to implement this, but I'm not sure how to call the file I make each time testn, with n being the current value of n. So I would have files: test1, test2 and so on.

My implementation so far is:

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()
5
  • What is the output its giving? Commented Mar 27, 2020 at 14:46
  • btw Please prefer to use with open(...) as newFile: Commented Mar 27, 2020 at 14:55
  • What is the difference between what I have and what you have suggested @quamrana ? Commented Mar 27, 2020 at 15:08
  • You can dispense with the newFile.close() and your files are automatically closed, even if there is an exception. Commented Mar 27, 2020 at 15:09
  • Ok, thanks. That will definitely come in handy. Commented Mar 27, 2020 at 15:10

3 Answers 3

4

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

or in python3.6+:

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

Sign up to request clarification or add additional context in comments.

Comments

2

This should work:

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

Comments

0

This code will work for you it will create 5 text files each file contain 10 random numbers between range that you define in your code:

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.