#๐Ÿ”’ read() works only one time in python

26 messages ยท Page 1 of 1 (latest)

shut ore
#

Here is my code:
f=open("path", "r")
while True:
while f.read()=="True":
print("output is true")
time.sleep(0.5)
file is txt and all it contains is "True" but for some reason this code writes in cmd only one time despite loop, anyone got ideas how to fix it?

boreal marshBOT
#

@shut ore

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

true solstice
#

that's how read works. It consumes the text of the file

#

what exactly are you trying to do?

shut ore
true solstice
#

Are you trying to get it to read from the file while you're typing in it?

shut ore
#

close() prob fixes it but I doubt it is right to do so

true solstice
#

Yeah, it's not going to detect new changes made to the file once it has been opened by python

#

it has to be reopened

#

What are you hoping to achieve with this though?

#

This doesn't really seem like a practical solve for anything

shut ore
#

and its super hard to work with some libraries in lua so it doesnt seem like it is possible to write my python code there

true solstice
#

I know pyside has a file listener so you can assign it a file path and it will emit a signal if the contents of the file change

shut ore
#

Here is my code:
f=open("path", "r")
while True:
while f.read()=="True":
print("output is true")
f.close()
time.sleep(0.5)
this gives error apparently

#

(Io operation on closed file)

true solstice
#
from PySide2 import QtCore, QtWidgets


def on_file_change(file):
    print(f'{file} has new contents!')

app = QtWidgets.QApplication()
watcher = QtCore.QFileSystemWatcher()
watcher.addPath('foo.txt')
watcher.fileChanged.connect(on_file_change)
app.exec_()
#

here's an example of doing it with pyside

shut ore
true solstice
#

any time foo.txt is modified at all, the on_file_change function will be called

violet breach
true solstice
#

this That's probably better

boreal marshBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.