读取.txt文件Python时出现问题

时间:2019-10-18 18:59:53

标签: python

请帮助我...我不知道该怎么做 它应该生成15个随机数,将奇数写入.txt文件中,然后读取它。

import random
f = open('text','w+')
numbers = []
for i in range(15):
    x = random.randint(0,25)
    if x%2 == 1:
        numbers.append(str(x))
        f.write(str(x) + ' ')
print(f.read())

4 个答案:

答案 0 :(得分:1)

如何?

import random
f = open('text','w+')
numbers = []
#for i in range(15):
while len(numbers) < 15:
    x = random.randint(0,25)
    if x%2 == 1:
        numbers.append(str(x))
        f.write(str(x) + ' ')
f.close()

rf = open('text','r')
print(rf.read())
rf.close()

所以我发现的问题之一是您的范围是15,但不一定每个值都是奇数。

我还关闭了文件,并以读取状态重新打开。

答案 1 :(得分:1)

以“写入”模式打开文件,写入数字,将其关闭,然后以“读取”模式打开。希望有帮助

import random
f = open('text.txt','w')
numbers = []
for i in range(15):
    x = random.randint(0,25)
    if x % 2 == 1:
        numbers.append(str(x))
        f.write(str(x) + ' ')
f.close()
f = open('text.txt', 'r')
print(f.read())
f.close()

答案 2 :(得分:0)

您可以在HttpClientHandler模式下打开文件。写完奇数后,应使用var handler = new HttpClientHandler(); handler.ServerCertificateCustomValidationCallback = (s, cert, chain, err) => true; using var client = new HttpClient(handler); [...] 跳到文件的开头,然后从文件中读取。像这样:

open('text', 'rw+')

答案 3 :(得分:0)

其中一个错误是,如果随机数是偶数,则不会将其添加到文件中-但是for i in range(15):会继续进行下一个迭代-因此,最终不会获得15个数字。

import random
numbers = []
# With/open is the preferred technique to write. 
# Use a separate with open to read at the end. 
# Dont try to keep reading and writing from the same file, while it stays open
with open('text','w+') as f: 
    for i in range(15): # This will loop 15 times
        x = random.randint(0,25) # Set the random int first, so the while loop can evaluate
        while x%2 == 0: # if X is even, This will keep looping until it is odd
            x = random.randint(0,25)
        numbers.append(str(x)) # Dont know what this is for
        f.write(str(x) + ' ')

print("----------------")
with open('text','r') as f: 
    print(f.read())