Python写入和读取随机数到文件

问题描述

我正在编写一个 Python 代码来将随机文件写入文件并从文件中读取相同的数字并将它们放入一个 int 列表

import random
import datetime

w = open("test.txt","w")
for n in range(0,2):
    w.write(str(random.randint(0,10000)))
    w.write(",")
w.write(str(random.randint(0,10000)))

f = open("test.txt","r")
myArray = f.read().split(',')
for i in range (0,len(myArray)):
    myArray[i] = int(myArray[i])

print(myArray)

但是当我运行代码时,我收到错误提示

Traceback (most recent call last):                                                                                                             
  File "main.py",line 13,in <module>                                                                                                         
    myArray[i] = int(myArray[i])                                                                                                               
ValueError: invalid literal for int() with base 10: '' 

我该如何解决这个问题?有没有其他方法可以将随机数写入文件然后放入列表?

解决方法

错误是,您在写入文件后没有关闭文件。所以什么都没有写。一种解决方案是使用自动关闭文件的上下文管理器(with 关键字):

import random
import datetime

with open("test.txt","w") as w:
    for n in range(0,2):
        w.write(str(random.randint(0,10000)))
        w.write(",")
    w.write(str(random.randint(0,10000)))

with open("test.txt","r") as f:
    myArray = f.read().split(",")

for i in range(0,len(myArray)):
    myArray[i] = int(myArray[i])

print(myArray)

打印:

[3998,6615,7496]
,

使用机器可读的格式(例如 JSON)可能会更好:

import random
import json

numbers = [random.randint(0,10000) for x in range(3)]

with open("test.txt","w") as f:
    json.dump(numbers,f)

# ...

with open("test.txt","w") as f:
    numbers = json.load(f)

print(numbers)
,

确保在写入后和读取前关闭文件。否则,您将读取一个空文件。最好的方法是使用文件作为上下文管理器。

with open("test.txt","r") as f:
    myArray = list(map(int,f.read().split(',')))

print(myArray)
,

您需要刷新您写入文件的内容。当文件关闭时,它会自动刷新。使用 with 可以避免手动调用 close:

with open("test.txt",10000)))

参考: How often does python flush to a file?

,

您可以尝试更改此部分:

f = open("test.txt","r")
myArray = f.read().split(',')
for i in range (0,len(myArray)):
    myArray[i] = int(myArray[i])

到:

f = open("test.txt",')
myArray = list(map(int,filter(None,myArray)))

使用内置的filter()方法可以过滤掉空字符串,内置的map()方法将给定迭代器中的每个元素映射到给定的函数。