-1

My concern is written below:

  1. Why does this code return this error?

    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)
    

    Error:

    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. Why does this code write only a single value to the file?

    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)
    

    This code is supposed to generate 10 random numbers and write them to the file rn.txt. What am I doing wrong?

Kale Kundert
  • 1,144
  • 6
  • 18
  • 8
    In your first code you try to read from a file you open for writing. In the second code you recreate the file during every run of the loop. – Matthias Aug 16 '21 at 16:15
  • @Matthias, you mean reopen instead of recreate? –  Aug 16 '21 at 16:32
  • 1
    Your indentation is confusing. As it stands, that's not executable. But I'm also unsure about what you're trying to achieve. Anyway, this may help you to get started:- https://stackoverflow.com/questions/6648493/how-to-open-a-file-for-both-reading-and-writing –  Aug 16 '21 at 16:33
  • 1
    @Sujay If one wants to write it like that the file should be opend in append-mode. But opening the file before the loop is a better idea. And of course reading the file makes no sense. – Matthias Aug 16 '21 at 16:45
  • Both of these result in the same error. You cannot read from a file that you have explicitly opened only for writing. – MisterMiyagi Aug 17 '21 at 10:04
  • Have a look at this image to better understand the different file opening modes https://stackoverflow.com/a/30566011/1362735 – heretolearn Aug 17 '21 at 10:05

1 Answers1

0

You're trying to perform both read and write operations to a file which is opened in read or write mode. Choose one at a time.

For example, the following could work:

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)
waykiki
  • 914
  • 2
  • 9
  • 19