编写一个程序,将随机创建的100个随机整数写入文件。 Python文件i / o

时间:2018-04-25 02:00:20

标签: python file random io integer

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,是问题的一部分吗?

3 个答案:

答案 0 :(得分:1)

在代码中进行以下更改。

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

您需要将数据从stdin转换为整数,输入函数的默认类型是字符串。

我希望这能解决你的问题。

答案 1 :(得分:0)

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

答案 2 :(得分:0)

您的代码中存在多个问题。第一个是random.randint(1,100)没有给你100个随机数,但是1(包括)和100(包括)之间的单个随机值,并且你的for循环有点bug(不要在这里使用输入,或者你想从用户那里读到什么?)。

接下来就是打开文件“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())