简体   繁体   中英

How to create a file and write a specified amount of random integers to the file in Python

Very new to Python and programming. The problem is Create a program that writes a series of random numbers to a text file. Each random number should be in the range of 1 to 5000. The application lets the user specify how many random numbers the file will hold. My code so far is as follows:

 from random import randint
 import os
 def main ():
     x = int(input('How many random numbers will the fille hold?: '))
     temp_file = open('temp.txt', 'w')
     temp_file.write(str(randint(1,5000)))
  main()

I am having trouble implementing the logic for writing a random integer 1-5000 to a file x amount of times(as entered by the user) Would I be using a for statement?

How about this?

from random import randint
import os
def main ():
     x = int(input('How many random numbers will the fille hold?: '))
     temp_file = open('temp.txt', 'w')
     for _ in range(x):
         temp_file.write(str(randint(1,5000))+" ")
     temp_file.close() 
main()

Consider this:

from random import randint 

def main(n):
  with open('random.txt', 'w+') as file:
    for _ in range(n):
      file.write(f'{str(randint(1,5000))},')

x = int(input('How many random numbers will the file hold?: '))
main(x)

Opening the file in 'w+' mode will overwrite any previous content in the file and if a file doesn't exist it will create it.

Since python 3 we can now use f-strings as a neat way of formatting strings. As a beginner I'd encourage you learn these new cool things.

Lastly, using the with statement means you won't need to explicitly close the file.

You can use a python package called numpy . It can be installed by pip using pip install numpy . Here is a simple code

import numpy as np
arr=np.random.randint(1,5000,20)
file=open("num.txt","w")
file.write(str(arr))
file.close()

In the 2nd line, the third parameter 20 specifies the number of random numbers to be generated. Instead of hard-coding, take the value from user

Thank you guys for the help, using LocoGris's answer i ended up with this code which answers my question perfectly, thank you, I knew I needed the for statement? the _ could be any letter correct?

from random import randint
import os
def main ():
     x = int(input('How many random numbers will the file hold?: '))
     temp_file = open('temp.txt', 'w')
     for _ in range(x):
         temp_file.write(str(randint(1,5000)) + '\n')
     temp_file.close() 
main()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM