0

According to python documentation r+ can be used to read and write and the stream is positioned at the beginning of the file.But when I run this code, the code does not show the first few letter and shows "erwhateverwhatever " when I run it several times. I have checked the text file and whateverwhateverwhatever is wirtten after running the code three times. But I see "erwhateverwhatever " for read. Anyone knows the reason?

file=open('test.txt', 'r+')
file.write('whatever')
print(file.read())
file.close()
Jack
  • 725
  • 1
  • 10
  • 27
  • Are you aware that files have a read/write position shared for both operations? Can you provide a [mcve]? Re-running this code with an appropriate ``file = open(..., 'r+')`` will not write the word thrice (it is overwritten), and if the previous content is ``whateverwhateverwhatever`` it will print ``whateverwhatever``, i.e. without the leading ``er``. – MisterMiyagi Nov 16 '20 at 17:27
  • https://stackoverflow.com/questions/14271216/beginner-python-reading-and-writing-to-the-same-file. Look at this thread to get more information – BhavinT Nov 16 '20 at 17:42

1 Answers1

0
file=open('test.txt', 'r+')
file.write('whatever')
file.seek(0)
print(file.read())
file.close()

It's better to use w+ flag so that even if your text.txt is not created. It will create automatically at the start of the program and even get the same output

BhavinT
  • 338
  • 1
  • 10
  • Thank you, I have two questions: 1-Is this a bug for windows or my code was wrong? 2- You said it is better to add w+, could you elaborate more. Thanks – Jack Nov 16 '20 at 18:22
  • 1) If you read the explanation given in that thread it explains the bug that was present in previous versions which is resolved in next versions. But in the thread it clearly specifies you to use fseek(). fseek(0) will read the file from start and that changes I made in the code if can see – BhavinT Nov 16 '20 at 18:29
  • 2) For example you have not created test.txt before running the program and used r+ flag it will throw an error stating text.txt file not found. But if you use w+ flag it will first create the file even if you haven't created a file previously before running the program – BhavinT Nov 16 '20 at 18:35