首页 > 解决方案 > 如何在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.")

标签: python

解决方案


读取文件的三种方法

  1. read()它以字符串的形式返回读取的字节。

    fileObject.read()

您还可以定义要读取的字节数

`fileObject.read([n]) //If n is not define, it will read the whole file`
  1. readline([n])它读取行并以字符串的形式返回,它只读取单行

    fileObject.readline([n])

  2. readlines()它读取文件的所有行并将每一行返回一个列表中的字符串元素

    fileObject.readlines()

希望能帮助到你


推荐阅读