txt文件写入数据错误
The error with the write data in txt file
程序
@client.event
async def on_message(message):
my_file = open("{0}.txt".format(message.author.id), "w")
myfile1 = open("{0}.txt".format(message.author.id), "r")
myfile1.read()
my_file.write(myfile1.read() ++ number)
my_file.close()
错误
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\senuk\AppData\Local\Programs\Python\Python35\lib\site-
packages\discord\client.py", line 307, in _run_event
yield from getattr(self, event)(*args, **kwargs)
File "overmind.py", line 821, in on_message
my_file.write(myfile1.read() ++ number)
数量=1
我正在尝试读取消息的数量,然后将它们显示在有关用户的统计信息中,但不明白错误是什么以及如何解决,也许有人知道?
您错误地混合了对同一个文件的读取和写入。
基本上你想先读,然后写。您正在用递增的数字一次又一次地覆盖同一个文件。
# needs import os
@client.event
async def on_message(message):
fileName = "{0}.txt".format(message.author.id)
if os.path.exists(fileName):
with open(fileName, "r") as readFile:
data = int(readFile.read())
else:
data = 0
with open(fileName, "w") as writeFile:
writeFile.write(str(data+1))
您也可以使用 r+ 打开并在读取后截断文件 - 不过您需要在截断之后使用 seek(0),因为截断不会对文件指针执行任何操作:
参见:
程序
@client.event
async def on_message(message):
my_file = open("{0}.txt".format(message.author.id), "w")
myfile1 = open("{0}.txt".format(message.author.id), "r")
myfile1.read()
my_file.write(myfile1.read() ++ number)
my_file.close()
错误
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\senuk\AppData\Local\Programs\Python\Python35\lib\site-
packages\discord\client.py", line 307, in _run_event
yield from getattr(self, event)(*args, **kwargs)
File "overmind.py", line 821, in on_message
my_file.write(myfile1.read() ++ number)
数量=1
我正在尝试读取消息的数量,然后将它们显示在有关用户的统计信息中,但不明白错误是什么以及如何解决,也许有人知道?
您错误地混合了对同一个文件的读取和写入。 基本上你想先读,然后写。您正在用递增的数字一次又一次地覆盖同一个文件。
# needs import os
@client.event
async def on_message(message):
fileName = "{0}.txt".format(message.author.id)
if os.path.exists(fileName):
with open(fileName, "r") as readFile:
data = int(readFile.read())
else:
data = 0
with open(fileName, "w") as writeFile:
writeFile.write(str(data+1))
您也可以使用 r+ 打开并在读取后截断文件 - 不过您需要在截断之后使用 seek(0),因为截断不会对文件指针执行任何操作:
参见: