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

Is there a way in python 3 to retrieve data from file which has been read to end and then written some data?

I have a python script which lets me read file to end and after the reading if I enter ‘q’ then the script tries to read next data. But the script does not retrieve data after I enter ‘q’.

What I did

I have a file text.txt. I open this file in a text editor and enter "qwe" string and save it.
I run the python script:

with open("text.txt", "r") as f:
    print(f.read())
    if input() == "q":
        print(f.read())

And it prints "qwe".

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

Then I enter "123" string at the new line in file editor and save it.
Then I enter "q" at the script and see nothing is printed. But I expected to see "qwe" in one line and "123" in second line.

>Solution :

File editors are rather clever tools. In order not to lose data in bad conditions, many rename the original file and then save the new file on a plain different file. If anything goes wrong the original file has just to be renamed back, and at least it is still there, and if everything is good the original file is simply removed (or kept as a backup).

But for your use case, the file that your program has an handle on is never modified…

If you want to be able to change a file while a program is using it, you’d better write at the end with >>:

echo "123" >> text.txt
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