简体   繁体   English

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

[英]Problems reading a .txt file Python

Please help me guys... I do not know how to do this It should generate 15 random numbers, write the odd ones into a .txt file and then read it.请帮帮我......我不知道该怎么做它应该生成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())

How about this:这个怎么样:

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

So one of the problems i spotted was that you range 15 but not necessarily every value will be odd.所以我发现的一个问题是你的范围是 15,但不一定每个值都是奇数。

I also close the file and re-opened it as read.我还关闭了文件并以已读的方式重新打开它。

Open file in "write" mode, write numbers, close it, and then open it in "read" mode.以“写”模式打开文件,写入数字,关闭它,然后以“读”模式打开它。 Hope that helps希望有帮助

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

You can open your file in open('text', 'rw+') mode.您可以在open('text', 'rw+')模式下打开文件。 When you finish with writing odd numbers, you should jump to the start of the file using f.seek(0, 0) and then read form it.当你写完奇数时,你应该使用f.seek(0, 0)跳转到文件的开头,然后读取它。 Like this:像这样:

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

One of the bugs was, if the random number was even, it didn't get added to the file - but the for i in range(15): continues to the next iteration - so you don't end up with 15 numbers.其中一个错误是,如果随机数是偶数,它不会被添加到文件中 - 但是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