簡體   English   中英

編寫一個程序,將隨機創建的 100 個隨機整數寫入一個文件。 Python文件輸入/輸出

[英]Write a program that writes 100 random integers created randomly into a file. Python File i/o

import random

afile = open("Random_intger.txt", "w")
for i in range(input("The 100 random integers written are: ")):
    line = str(random.randint(1,100))
    afile.write(line)
    print(line)
afile.close()

print("\nReading the file now." )
afile = open("Random_integer.txt", "r")
print(afile.read())
afile.close()

當我運行它時:

  • 它說TypeError: 'str' object cannot be interpreted as an integer
  • 它創建標有Random_intger.txt的文件,但沒有整數。
  • 另外,我使用的是 MacBook Air,這是問題的一部分嗎?

在您的代碼中進行以下更改。

for i in range(**int(input("The 100 random integers written are: "))**):

您需要將數據從標准輸入轉換為整數,輸入函數的默認類型是字符串。

我希望這能解決你的問題。

您的代碼中有多個問題。 第一個是 random.randint(1,100) 不是給你 100 個隨機數,而是一個介於 1(含)和 100(含)之間的隨機值,而且你的 for 循環有點問題(不要在這里使用輸入,或者你想從標准輸入中讀取一些東西?)。

下一件事:您正在打開文件“Random_intger.txt”以將您的數字寫入其中。 但是您從文件“Random_int e ger.txt”中讀取...

固定代碼:

import random

filename = "Random_integer.txt"

# use a with statement. Like this you don't need to
# remember to close the stream ...
with open(filename, "w") as afile:
    print("The 100 random integers written are: ")
    for i in range(100):
        line = str(random.randint(1,100))
        afile.write(line)
        afile.write("\n")
        print(line)

print("\nReading the file now." )
with open(filename, "r") as afile:
    print(afile.read())
import random
out_file = "Random_integer.txt"
afile = open(out_file, "w")
for i in range(100):
    line = str(random.randint(1,100)) + '\n'
    afile.write(line)
    print(line)

afile.close()

print("Reading the file now." )
afile = open(out_file, "r")
print(afile.read())
afile.close()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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