python - 如何在python中读取外部文件?
问题描述
我需要能够从外部文件中保存和获取用户名和密码。这是我到目前为止所做的,但是即使我输入正确,它也经常说用户名或密码不正确。有谁知道如何解决这个问题。
这是我当前的代码
import time
print("Welcome...")
welcome = input("Do you have an acount? y/n: ")
if welcome == "n":
while True:
username = input("Enter a username:")
password = input("Enter a password:")
password1 = input("Confirm password:")
if password == password1:
file = open("gcsetask.txt", "a")
file.write(username + ":" + password)
file.write('\n')
file.close()
welcome = "y"
time.sleep(0.4)
print("now lets login")
break
print("Passwords do NOT match!")
if welcome == "y":
while True:
login1 = input("Enter username:")
login2 = input("Enter Password:")
file = open("gcsetask.txt", "r")
data = file.readlines()
file.close()
if data == (login1 + ":" + login2):
print("Welcome")
break
print("Incorrect username or password.")
解决方案
读取文件的三种方法
read()
它以字符串的形式返回读取的字节。fileObject.read()
您还可以定义要读取的字节数
`fileObject.read([n]) //If n is not define, it will read the whole file`
readline([n])
它读取行并以字符串的形式返回,它只读取单行fileObject.readline([n])
readlines()
它读取文件的所有行并将每一行返回一个列表中的字符串元素fileObject.readlines()
希望能帮助到你
推荐阅读
- visual-studio - Visual Studio 调试器不适用于 F10
- java - 在 Java 中使用另一个类作为方法 - 这叫什么?
- scrapy - 如何从 Scrapy 输出中删除 \n \t 但在那里留下 HTML 标签
- javascript - 如何使函数在映射数组中的单个项目上执行,而不是在数组中的每个项目上执行?
- javascript - 如何根据laravel中的选定下拉菜单重定向到另一个页面
- node.js - Mongodb返回错误:“data”参数必须是字符串类型或Buffer、TypedArray或DataView的实例。收到 MongoError 的实例
- swiftui - 不在小部件中时如何设置 .widgetFamily @Environment 变量?
- html - 内联 flex 添加空格
- firebase - 错误:错误状态:DocumentSnapshotPlatform 中不存在字段
- android - 评估项目 ':app' 时出现问题。Flutter 构建 Appbundle 错误