0

I am using VSC for writing python scripts to read/write file. I am able to write file using the below code:

with open("score_card.txt", mode="w+") as file_data:
    file_data.write("23")

but when trying to read the file using the below code:

with open("score_card.txt", mode="w+") as file_data:
    print(file_data.read())

it is not giving anything in the terminal.

1 Answers1

0

You need to open the file in read mode. Here's an example:

with open("score_card.txt", mode="r") as file_data:
    print(file_data.read())

You can learn more about the open function modes here https://docs.python.org/3/library/functions.html#open

An important thing to remember is that the w+ mode is for truncating and writing. This means that it will wipe the file contents, so when you try to read it, there is nothing in the file. You should use mode='r' on all files that you don't intend to edit.

Joe
  • 497
  • 1
  • 3
  • 11
  • Hi Joe, Yes I tried that as well still same issue, I am able to write anything in file but not able to read it. – Bilal Zafri Sep 04 '22 at 17:36
  • If you previously opened it in `w+` mode, the file was wiped and is empty now. I'd recommend checking the file and adding some lines to it then trying again with `r` mode. – Joe Sep 04 '22 at 17:37
  • Just tried still not working, also there is data in the file before reading I am cross-checking. do you think it might be some VS or permission issue? Although I am not getting any such warning. – Bilal Zafri Sep 04 '22 at 17:45
  • 1
    Looks like it was some project directory issue, Create the same project in a new directory and now able to read and write. – Bilal Zafri Sep 04 '22 at 18:09