[英]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.