繁体   English   中英

如何在一行中写入 2 个值并稍后再次读取它们? Python

[英]How to write 2 values in one line and read them later again? Python

我想创建一个将登录信息保存在文件中的程序。 所以我认为最好的方法是这样写用户名和密码:

username # password

但是如何翻动它以及如何再次阅读它呢? 我的代码用 3 行而不是 1 行编写:

file = open(“testfile.txt”,”w”) 

file.write(username) 
file.write(“#”) 
file.write(password) 

file.close() 

file = open(“testfile.txt”, “r”)
print file.read(1)

如何让程序只写一行?

编辑我需要再次保存到变量中的 2 个值。

这将让您在一行中写下用户名和密码:

username, password = 'username', 'password'

with open("testfile.txt", 'w') as file:
    file.write(f"{username} # {password}")

从您的文件中读取

lines = [] 
with open('testfile.txt', 'r') as file:
    for line in file:
        lines.append(line)
print(lines[0]) # this will print line 1 

对于阅读,您可以使用拆分 function:

print(file.readline().split('#'))

暂无
暂无

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

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