我正在尝试将数据写入.txt文件。正在编写的数据是以下代码中randrange
函数的随机整数
在尝试写入文件时,我不断收到错误,指出对象没有属性
请帮忙。
import random
def main():
file_size = open('numbers.txt','w')
file_size = random.randint(4, 7)
print("file_size = ", file_size)
for _ in range(file_size):
random_num = random.randrange(5,20,2)
if random_num % 2 ==1:
print(random_num)
file_size.write(str(random_num))
file_size.close()
print('Data has been written.')
main()
答案 0 :(得分:0)
你有一个大错误,因为file_size
首先是一个流然后是一个int
您必须为file
和file_size
另外我想你想把循环中的每个数字写入文件,因此它必须进入你的if-block:
import random
def main():
file = open('numbers.txt', 'w') #rename to file
file_size = random.randint(4, 7)
print("file_size = ", file_size)
for _ in range(file_size):
random_num = random.randrange(5, 20, 2)
if random_num % 2 == 1:
print(random_num)
#use file not file_size
file.write(str(random_num)+'\n') #write every odd number to stream?
#use file not file_size
file.close()
print('Data has been written.')
main()