0

enter image description hereI created a file name rishi.txt and then added "HELLO WORLD" to it then read() it. after that, I closed and opened it with w+ mode. Then I wrote "BYE" and when read() the file it shows an Output: ' '.

 [![This is the image of my code and the output][1]][1]
  • Reading *and* writing moves the file pointer. You have to ``.seek(0)`` to the beginning if you want to read what you wrote. – MisterMiyagi Mar 22 '20 at 10:13
  • Have you tried to see what text is in the file without opening it in Python? – oscarfrederiksen Mar 22 '20 at 10:14
  • 1
    As per SO guidelines, all code, data, error messages, etc MUST be input as TEXT (and formatted as code, or, for error messages, quote formatting). Screenshots can be difficult to read, especially on mobile devices. Furthermore, volunteers need the ability to copy-paste your code into their editors to check, debug, and tests your code and their solutions into their editors, or to paste error messages into Google. To help efficiently, and without introducing their own errors. Please read [how to ask](StackOverflow.com/help/how-to-ask), and other topics in the help section, then `edit` your post. – SherylHohman Mar 22 '20 at 15:54

1 Answers1

2

From: https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects

To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string (in text mode) or bytes object (in binary mode). size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as large as your machine’s memory. Otherwise, at most size characters (in text mode) or size bytes (in binary mode) are read and returned. If the end of the file has been reached, f.read() will return an empty string ('').

You will have to use either a contextmanager and do:

with f as open( 'rishi.txt'):
    f.read()

or call:

asdf.seek(0)
yayg
  • 309
  • 2
  • 12