[英]How to create a file and write a specified amount of random integers to the file in Python
Python 和編程非常新。 問題是創建一個將一系列隨機數寫入文本文件的程序。 每個隨機數應該在 1 到 5000 的范圍內。應用程序允許用戶指定文件將保存多少個隨機數。 到目前為止,我的代碼如下:
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()
我在實現將隨機 integer 1-5000 寫入文件 x 次數(由用戶輸入)的邏輯時遇到問題 我會使用 for 語句嗎?
這個怎么樣?
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()
考慮一下:
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)
以“w+”模式打開文件將覆蓋文件中任何以前的內容,如果文件不存在,它將創建它。
由於 python 3 我們現在可以使用f-strings作為格式化字符串的一種簡潔方式。 作為初學者,我鼓勵你學習這些新的很酷的東西。
最后,使用with
語句意味着您不需要顯式關閉文件。
您可以使用名為 numpy 的 python numpy
。 它可以通過 pip 使用pip install numpy
。 這是一個簡單的代碼
import numpy as np
arr=np.random.randint(1,5000,20)
file=open("num.txt","w")
file.write(str(arr))
file.close()
在第 2 行中,第三個參數20
指定要生成的隨機數的數量。 從用戶那里獲取價值,而不是硬編碼
謝謝你們的幫助,使用 LocoGris 的回答我最終得到了這段代碼,它完美地回答了我的問題,謝謝,我知道我需要 for 語句? _ 可以是任何正確的字母嗎?
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.