3

I need to call a routine inside a loop which takes a text file as input. Because I don't want to open and close the text file all the time I keep it open in the loop. For Example:

with open("test.txt",'r+') as w_file:

    w_file.write(str(0.8) + "\n" + str(0.2))
    subprocess.call(["cat","test.txt"]) #Here I want to call my routine

But the file is still in the old state. Why? And whats the best way to handle this?

2
  • 3
    Try w_file.flush() after your write line, but before the subprocess.call line. Commented Feb 3, 2016 at 14:31
  • unrelated: you could use print() function: print(0.8, 0.2, sep="\n",file=w_file) or string formatting: w_file.write("{}\n{}".format(0.8, 0.2)) Commented Feb 4, 2016 at 14:34

2 Answers 2

3

you need to close the file after writing. try:

with open("test.txt",'r+') as w_file:
    w_file.write(str(0.8) + "\n" + str(0.2))

subprocess.call(["cat","test.txt"]) #Here I want to call my routine

or without closing, flush the file

with open("test.txt",'r+') as w_file:
    w_file.write(str(0.8) + "\n" + str(0.2))
    w_file.flush()
    subprocess.call(["cat","test.txt"]) #Here I want to call my routine
Sign up to request clarification or add additional context in comments.

1 Comment

use w mode instead of r+ to overwrite the file.
0

This should work:

with open("test.txt",'r+') as w_file:
    w_file.write(str(0.8) + "\n" + str(0.2))
    w_file.flush()
    subprocess.call(["cat","test.txt"])

The method "flush" syncs the actual file referenced by the file-like object w_file with the contents still in memory, so when you reference the file by it's name (and not the w_file FLO), you see an up to date version.

1 Comment

Sorry I kept my window open for a while before posting my answer and didn't notice someone else had already answered. Please discard this one.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.