显示文件内容
Displaying the contents of the file
我在显示文件内容时遇到问题:
def NRecieve_CnD():
host = "localhost"
port = 8080
NServ = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
NServ.bind(("localhost",8080))
NServ.listen(5)
print("Ballot count is waiting for ballots")
conn, addr = NServ.accept()
File = "Ballot1.txt"
f = open(File, 'w+')
data = conn.recv(1024)
print('Ballots recieved initializing information decoding procedures')
while(data):
data1 = data.decode('utf8','strict')
f.write(data1)
data = conn.recv(1024)
print("Ballot saved, Now displaying vote... ")
files = open("Ballot1.txt", "r")
print(files.read())
当程序是运行时,应该显示文件内容的区域是空白的。
您正在写入一个文件,然后再次打开该文件并且没有显式刷新您的第一次写入,或者通过关闭文件句柄,您正在读取一个文件。结果是您在完成写入之前正在读取文件。
f.write(data1)
f.flush() # Make sure the data is written to disk
data = conn.recv(1024)
print("Ballot saved, Now displaying vote... ")
files = open("Ballot1.txt", "r")
除此之外,最好不要让文件打开的时间超过必要的时间,以避免出现如下意外情况:
with open(File, 'w+') as f:
f.write(data1)
data = conn.recv(1024)
print("Ballot saved, Now displaying vote... ")
with open(File, "r") as f:
print(f.read())
我在显示文件内容时遇到问题:
def NRecieve_CnD():
host = "localhost"
port = 8080
NServ = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
NServ.bind(("localhost",8080))
NServ.listen(5)
print("Ballot count is waiting for ballots")
conn, addr = NServ.accept()
File = "Ballot1.txt"
f = open(File, 'w+')
data = conn.recv(1024)
print('Ballots recieved initializing information decoding procedures')
while(data):
data1 = data.decode('utf8','strict')
f.write(data1)
data = conn.recv(1024)
print("Ballot saved, Now displaying vote... ")
files = open("Ballot1.txt", "r")
print(files.read())
当程序是运行时,应该显示文件内容的区域是空白的。
您正在写入一个文件,然后再次打开该文件并且没有显式刷新您的第一次写入,或者通过关闭文件句柄,您正在读取一个文件。结果是您在完成写入之前正在读取文件。
f.write(data1)
f.flush() # Make sure the data is written to disk
data = conn.recv(1024)
print("Ballot saved, Now displaying vote... ")
files = open("Ballot1.txt", "r")
除此之外,最好不要让文件打开的时间超过必要的时间,以避免出现如下意外情况:
with open(File, 'w+') as f:
f.write(data1)
data = conn.recv(1024)
print("Ballot saved, Now displaying vote... ")
with open(File, "r") as f:
print(f.read())