Open prompts [Errno 22] Invalid argument when opening a string variable

topic description

define a variable whose value is the absolute path of the file to be operated. Use the open function to open invalid arguments

when you want to operate.

sources of topics and their own ideas

there is no problem with testing with the print function. It is normal to print logfile, but it is not normal to open it in open.

related codes

-sharp! python3
-sharp -*- encoding:utf-8 -*-



import os
import sys
import time



if os.path.isdir("logs"):
    pass
else:
    os.mkdir("logs")

log_path = os.path.join(os.getcwd(),"logs",time.asctime())
logfile = os.path.normcase(log_path) + ".log"

with open(logfile,"wb") as lf:
    lf.write("test")

what result do you expect? What is the error message actually seen?

error message: OSError: [Errno 22] Invalid argument: "e:\ python\ remote Administration\ logs\ tue sep 18 17:50:23 2018.log"

Jul.01,2021

the problem lies in lf.write ("test") . Why? Because your file is opened in the form of wb , that is, it is opened in the form of binary stream or byte, but here lf.write ("test") is written as a string, so there is an error. The correct action should be:

< H1 > lf.write (b "test") < / H1 >

in this case, write a string of type byte.

Menu