Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
105 views
in Technique[技术] by (71.8m points)

python - Trying to make a log function

I want to make a log function in my script but I don`t know why it gives me this error

File "c:/Users/x/x/x", line 33
    log = open(f"Log/{realDate.strftime("%x")}.txt", "a")
                                                  ^
SyntaxError: invalid syntax

Here`s the code that is causing the problem

realDate = datetime.datetime.now()
    log = open(f"Log/{realDate.strftime("%x")}.txt", "a")
    log.write("Hello Stackoverflow!")
    log.close()

Can somebody please help me?

question from:https://stackoverflow.com/questions/66068640/trying-to-make-a-log-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem is that you are trying to nest double quotes inside double quotes; f-strings don't allow that. You would need to change one or the other to another style of quotes. For example:

log = open(f'Log/{realDate.strftime("%x")}.txt', "a")

The main problem is that you aren't using a version of Python that supports f-strings. Make sure you are using Python 3.6 or later. (Update: Even in Python 3.6 or later, the identified location of the error can shift:

>>> f"{print("%x")}"
  File "<stdin>", line 1
    f"{print("%x")}"
                   ^
SyntaxError: invalid syntax
>>> f"{print("x")}"
  File "<stdin>", line 1
    f"{print("x")}"
              ^
SyntaxError: invalid syntax

)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...