简体   繁体   English

需要帮助在 Python 中创建 txt 日志文件

[英]Need help creating a txt log file in Python

I am stuck on an assignment: We have to make a password checker with a txt log file logging the time and date a password was put it, but only if the password doesn't meet the requirements to be accepted.我被困在一项任务中:我们必须使用 txt 日志文件制作一个密码检查器,记录密码输入的时间和日期,但前提是密码不符合被接受的要求。

The password checker code is below, I need some help with logging to a file.密码检查器代码如下,我需要一些有关登录文件的帮助。

PASSWORD_MIN_LENGTH = 6
PASSWORD_MAX_LENGTH = 14

password = input("Enter your password: ")

password_length = len(password)

while password_length < PASSWORD_MIN_LENGTH or password_length > PASSWORD_MAX_LENGTH:
    print("Error - password out of range")
    password = input("Enter new password between 6 and 14 characters: ")
    password_length = len(password)

if password.isdigit():
    message = "your password is too weak"
elif password.isalpha():
    message = "your password is too weak"
else:
    message = "your password is strong"

print(f"{message} your password length was: {password_length}")

Any suggestions?有什么建议?

You can use f = open("file.txt", "w") for creating and writing to a text file, if the file with the name file.txt already exists, it will not create a new one but it finds that file and writes to it.您可以使用f = open("file.txt", "w")来创建和写入文本文件,如果名称为file.txt的文件已经存在,则不会创建新的文件,但会找到该文件并写信给它。 To start writing to the file, simply use f.write("Your message") .要开始写入文件,只需使用f.write("Your message") When finished, use f.close() to close the file.完成后,使用f.close()关闭文件。

As an answer to your question, you can create a function that logs the password given to it to a text file.作为您问题的答案,您可以创建一个函数,将提供给它的密码记录到文本文件中。 I have create the following function to write the password to a text file:我创建了以下函数来将密码写入文本文件:

from datetime import datetime

def logPassword(password, filename):
    f = open(filename, "a")
    f.write("{0} -- {1}\n".format(datetime.now().strftime("%Y-%m-%d %H:%M"), password))
    f.close()

The function writes the date, time and password in the following format to the txt file:该函数将日期、时间和密码按以下格式写入 txt 文件:

2019-04-18 09:58 -- test1
2019-04-18 09:58 -- test2
2019-04-18 09:58 -- test3

The "a" in the open(filename, "a") function means that you are appending to the text file so nothing in the file will be overwritten."a"open(filename, "a")的功能意味着你追加到文本文件,因此没有在文件中都将被覆盖。

To use this function in your code just call it when validating the password.要在您的代码中使用此函数,只需在验证密码时调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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