繁体   English   中英

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

[英]Problems reading a .txt file 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())

这个怎么样:

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,但不一定每个值都是奇数。

我还关闭了文件并以已读的方式重新打开它。

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

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

您可以在open('text', 'rw+')模式下打开文件。 当你写完奇数时,你应该使用f.seek(0, 0)跳转到文件的开头,然后读取它。 像这样:

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

其中一个错误是,如果随机数是偶数,它不会被添加到文件中 - 但是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())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM