简体   繁体   中英

I cant use open() in python

i use amd and 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.

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() . Strings will be written after the file is closed.

An alternative would be 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.

So you'll need a .flush() call after every .write() call to write your changes to the disk right away.

(Also,you don't need a global f if you're already in the global scope.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM