Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python3 How could i make Reading and writing using With

Hello How i could make Python Write and Read at the sametime using (with) i did this simple function to add names in txt file but the output is usully empty…

def student():
    with open("students.txt","w+") as my_file:
        for i in range(20):
            user = input("Enter your name : ")
            my_file.write(f"{user}\n")
        print(my_file.read())

student()

tried r+ w+ a+ but none of them were working only r works but then i can’t add to the file

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to reposition the cursor to the start of the file, write moves it to the end:

def student():
    with open("students.txt", "w+") as my_file:
        for i in range(20):
            user = input("Enter your name : ")
            my_file.write(f"{user}\n")

        my_file.seek(0)  # reposition cursor to start of file
        print(my_file.read())

student()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading