【问题标题】:Random No Generator随机无发生器
【发布时间】:2021-08-16 16:12:07
【问题描述】:

我的担忧写在下面:

  1. 为什么这段代码会返回这个错误?

    import random
    with open('rn.txt', 'w') as f:
        for i in range(10):
            number = random.random()
            f.write(str(number) + '\n')
            content=f.read()
    print (content)
    

    错误:

    Traceback (most recent call last)
    <ipython-input-11-ddb88b6f5426> in <module>
          4         number = random.random()
          5         f.write(str(number) + '\n')
    ----> 6         content=f.read()
          7 print (content)
    
    UnsupportedOperation: not readable
    
  2. 为什么这段代码只向文件写入一个值?

    import random
    for i in range(10):
        with open('rn.txt', 'w') as f:
            number = random.random()
            f.write(str(number) + '\n')
            content=f.read()
            print (content)
    

    这段代码应该生成10个随机数并将它们写入文件rn.txt。我做错了什么?

【问题讨论】:

  • 在您的第一个代码中,您尝试从打开的文件中读取数据。在第二个代码中,您在每次循环运行期间重新创建文件。
  • @Matthias,你的意思是重新打开而不是重新创建?
  • 您的缩进令人困惑。就目前而言,这是不可执行的。但我也不确定你想要达到的目标。无论如何,这可能会帮助您入门:- stackoverflow.com/questions/6648493/…
  • @Sujay 如果想这样写,文件应该以附加模式打开。但是在循环之前打开文件是一个更好的主意。当然,阅读文件是没有意义的。
  • 这两个都会导致相同的错误。你不能从一个你明确打开的文件中读取数据。

标签: python python-3.x python-requests


【解决方案1】:

您正尝试对以读取写入模式打开的文件执行读取写入操作。一次选择一个。

例如,以下可能有效:

import random

# first open the file in Write mode ('w')
with open('rn.txt', 'w') as f:
    for i in range(10):
        f.write(str(random.random()) + '\n')

# now open the file in Read mode ('r')
with open('rn.txt', 'r') as f:
    for line in f:
        print(line)

【讨论】:

    猜你喜欢
    • 2011-01-23
    • 2019-12-15
    相关资源
    最近更新 更多