[英]python readlines() function
我刚开始使用 pthon 学习文件处理并尝试将其作为代码但由于某种原因我的 readlines() function 返回一个空列表我在 UsernameAndPassword.txt 文件中保存了一个名称和密码
path1="C:/Users/om/UsernameAndPassword.txt"
f1=open(path1,'a+')
l1=f1.readlines()
print(l1)
def main():
un=input("Enter Username: ")
if un in l1:
i1=l1.index()
p1=l1[i1+1]
pcheck1=input("Enter Password: ")
if pcheck1==p1:
print("Succesfully Logged In!")
def main2():
f2=input("Enter Path of file you want to Access or Path of file you want to create\n")
if f2.exists()==True:
open(f2,'a+')
input1=input("Enter Text you want to write into the File(Enter Blank to stop and a space to leave a line)\n")
while True:
input2=input("\n")
if input2=="":
break
else:
f2.write(input1)
f2.write(input2)
input3=input("Do you want to Read the file?\n")
if input3=='Yes' or input3=='yes':
r1=f2.read()
print(r1)
else:
print("Do you want to access another file?")
input3=input("")
if input3=='yes' or 'Yes':
main2()
else:
print("Thank you for using this :)")
else:
print("File Path Invalid!")
input4=input("Try Again?\n")
if input4=='yes' or 'Yes':
main2()
else:
print("Thank you for using this :)")
main2()
else:
print("Wrong Password")
main()
else:
print("Wrong Username")
input5=int(input("Sign up(Enter 1) or Try again(Enter 2)\n"))
if input5==2:
main()
elif input5==1:
inp6=input("Enter New Username: ")
inp7=input("Enter Password: ")
f1.write(inp6)
f1.write(inp7)
main()
else:
print("Invalid Input")
print("Thank you for using this :)")
f2.close()
f1.close()
main()
a+
是一种文件模式,实际上意味着“能够 append 并读取”。 特别是,由于我们正在追加,它从文件的末尾而不是开头开始。 您可以将其想象成记事本或您最喜欢的文本编辑器中的 cursor:当您以r
模式打开文件时,cursor 从开头开始读取整个文件,但是当您以a
模式打开时,cursor从文件末尾开始,以便后续写入不会覆盖现有内容。
在你的情况下,因为你只是从文件中读取,所以只需使用r
模式。
f1 = open(path, 'r')
如果您确实需要a+
(同样,您向我们展示的代码段不需要,但您的实际要求可能有所不同),那么您可以手动搜索到文件的开头以进行阅读。
f1 = open(path, 'a+')
f1.seek(0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.