0

So I'm making a python program that allows 2 people to talk to each over. The issue I'm having is that the texts only update whenever you write something. I'm not sure if there is a solution but if someone has one I'd appreciate it. Here's my code:

import os
import filecmp
import threading
username = input("Enter a Username: ")

file = open("chat.txt","w")
file.truncate(0)
file.close()


os.system("cls")
message = ""



def writing():
    global message
    with open("chat.txt", "a") as g:
        b = input("Send message: ")
        os.system("cls")
        message = username+": "+ b
        g.write(message)
        g.write("\n")
def reading():
    os.system("cls")
    with open("chat.txt", "r") as f:
        for line in f:
            print(line)


while 2>1:
    writing()
    reading()

I'm kind of new to python so I may be missing something obvious.

mmm
  • 1
  • also, running cls to clear the screen... sounds like a bit of a bad choice. I'm not 100% sure of the semantics of `file.write` on Python, but file IO is usually buffered – there's actually no guarantee the line appears in the file the moment you `g.write(message)`. Plain files are not the right tool to exchange data between processes! – Marcus Müller Nov 22 '21 at 19:22
  • Even if that works, there's a fundamental logical bug in your software: many operating systems (and windows, especially, seeing you use `cls`) will lock a file so that it can't be opened while another process is writing to it, and that can take arbitrarily long; your code just breaks when that happens! – Marcus Müller Nov 22 '21 at 19:25

0 Answers0