简体   繁体   English

如何在 python 中使用 append 添加文本

[英]How to add text using append in python

So I created python password generator.所以我创建了 python 密码生成器。 I want the password created to add itself to a txt file but I cant find a way.我希望创建的密码将自己添加到 txt 文件中,但我找不到方法。 Heres the code:继承人的代码:

 import random passlen = int(input("enter the length of password ")) s="abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ?@#$%^&*()." p = "".join(random,sample(s.passlen )) file = open("pass,txt". "a") file:write("Password. ") file.close() print(p) file = open("pass,txt". "r") print("Output of Readlines after appending") print(file.read()) print() file close()
with open("pass.txt", "r") as myfile:
myfile.write(p)

hope this help希望这有帮助

You are not writing p into file .您没有将p写入file Try:尝试:

import random

passlen = 10
s = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()?"

p = ''.join(random.sample(s, passlen))

with open('pass.txt', 'a') as f:
    print(f"password: {p}", file=f)

with open('pass.txt', 'r') as f:
    print("Now the contents of pass.txt:")
    print(f.read())

Note that with open is preferred (to open ... close ) in general.请注意,通常首选with openopen ... close )。

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

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