[英]I cant use open() in python
i use amd and windows.我使用 AMD 和 windows。
im coding a way to automate a discord bot to win, because me and some friends are competing against each other, my problem is that i want the program to log each time it does something, but i cant write into my file here is the code.我正在编写一种自动化 discord 机器人获胜的方法,因为我和一些朋友正在相互竞争,我的问题是我希望程序在每次执行某些操作时都记录下来,但我无法写入我的文件这里是代码.
import pyautogui
from threading import Thread
import threading
import datetime
from time import sleep
now = datetime.datetime.now()
date="[" + str(now.year) + "/" + str(now.month) + "/" + \
str(now.day) + "/" + str(now.hour) + "/" + \
str(now.minute) + "/" + str(now.second) + "]"
global f
f=open("log.txt", "a")
f.write("started")
def hunt():
global f
pyautogui.typewrite("owo h")
pyautogui.press("enter")
print("Owo acaba de cazar")
f.write(date + "Succesfuly hunted")
threading.Timer(31.0, hunt).start()
def pray ():
global f
pyautogui.typewrite("owo pray")
pyautogui.press("enter")
print("Owo acaba de hacer pray")
f.write(date +"Succesfuly prayed")
threading.Timer(300.0, pray).start()
f.write("popo")
Thread(target = hunt).start()
sleep(1)
Thread(target = pray).start()
You forgot to close your file at the end of your script f.close()
.您忘记在脚本
f.close()
结束时关闭文件。 Strings will be written after the file is closed.文件关闭后将写入字符串。
An alternative would be with open(...)
:另一种方法是
with open(...)
:
with open('log.txt', 'a') as file:
file.write('text\n')
If you use 'open' command you must use close it after getting the work done.如果您使用“打开”命令,您必须在完成工作后使用关闭它。 For examle:
例如:
f = open('file.txt', "a")
f.write("something")
f.close() # For to save all changes.
You didn't .flush()
the file,which means your .write()
calls(which write to a buffer) stay in the buffer and doesn't write to the disk.您没有
.flush()
文件,这意味着您的.write()
调用(写入缓冲区)留在缓冲区中并且不写入磁盘。
So you'll need a .flush()
call after every .write()
call to write your changes to the disk right away.因此,您需要在每次
.write()
调用后立即调用.flush()
将更改写入磁盘。
(Also,you don't need a global f
if you're already in the global scope.) (另外,如果您已经在全局 scope 中,则不需要
global f
。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.