如何添加段落写入文件

时间:2015-09-06 14:02:05

标签: python python-3.x

我的代码:

file_object = open("file.txt","w")
username = input("Enter your username here: ")
password = input("Enter your password here: ")
file_object.write(username)
file_object.write(password)
file_object.close()

如何将用户名和密码与输出文件(file.txt)上的段落分开?

3 个答案:

答案 0 :(得分:1)

如果您希望每个用户名和密码位于不同的行,则需要添加换行符,还需要打开mode设置为a每次附加新数据,而不是每次都覆盖你重新打开文件:

with open("file.txt","a") as file_object:
    username = input("Enter your username here: ")
    password = input("Enter your password here: ")
    file_object.write("{},{}\n".format(username, password))

因此,username = "foopassword = 1234会将foo,1234写入您的文件,然后在下一个输入username = "barpassword = 5678上输出文件将如下所示:

foo,1234
bar,5678

使用with表示您的文件  将自动关闭,因此无需显式调用close

答案 1 :(得分:0)

一个简单的file_object.write("\n")应该创建一个换行符 \n是换行符转义序列

答案 2 :(得分:0)

添加了更好的密码处理:

from getpass import getpass

separator = ";"

with open("file.txt","w") as file_object:
    username = input("Enter your username here: ")
    password = getpass("Enter your password here: ")
    file_object.write(separator.join([username, password]) + "\n")