[英]Python won't read text file
我試過在網上尋找解決這個問題的方法,但沒有任何效果。
Python 應該讀取一個名為“directory.txt”的文件,但它不斷出現空白或說:
<_io.TextIOWrapper name='directory.txt' mode='r' encoding='cp1252'>
這個想法是它應該讓用戶將姓名和電子郵件添加到 txt 文件中,允許他們“讀取”文件或“添加”到它。
代碼:
command = input("What would you like to do? Read or add? >> ")
programactive = True
if command == "Read" or "read":
directory = open('directory.txt', 'r')
directory.read()
print(directory)
directory.close()
elif command == "Add" or "add":
while programactive == True:
directory = open('directory.txt', 'a')
new_name = input("Add a new name to the list. >> ")
new_email = input("Add a new email for that name. >> ")
combined = new_name + ", " + new_email
directory.write(combined)
cont = input("Add more? Yes or No >> ")
if cont == "No" or "no":
directory.close()
programactive = False
我在這里寫了代碼,它正在工作:
import io
programactive = True
command = input("What would you like to do? Read or add? >> ")
if command == "Read" or command == "read":
directory = open("directory.txt", 'r')
read_string = directory.read()
print(read_string)
directory.close()
elif command == "Add" or command == "add":
while programactive == True:
directory = open('directory.txt', 'a')
new_name = input("Add a new name to the list. >> ")
new_email = input("Add a new email for that name. >> ")
combined = new_name + ", " + new_email + ", "
directory.write(combined)
cont = input("Add more? Yes or No >> ")
if cont == "No" or "no":
directory.close()
programactive = False
else:
print("Invalid command...")
我在這段代碼中看到的一些問題:
1)您正在打印指向directory
對象的內存位置的指針,而不是其內容。
2) 您的Read
和Add
和No
條件邏輯沒有正確檢查這兩個條件。 3)您不會在每個添加的條目后附加換行符,因此文本將顯示在一行上,而不是分隔符。
對於#1,您只需要將directory.read()
的內容存儲在一個字符串變量中,然后打印該字符串,而不是打印對象本身。 對於#2,當您有多個相等條件時,您必須明確定義相等的兩邊(例如if command == "Read" or command == "read":
而不僅僅是if command == "Read" or "read:"
對於#3,您只需要在“組合”變量中添加一個\\n
即可。
嘗試以下代碼,並測試“添加”功能,然后檢查文件以確保添加的文本按照您的預期進行格式化:
command = input("What would you like to do? Read or add? >> ")
programactive = True
if command == "Read" or command == "read":
directory = open('directory.txt', 'r')
contents = directory.read()
print(contents)
directory.close()
elif command == "Add" or command == "add":
while programactive == True:
directory = open('directory.txt', 'a')
new_name = input("Add a new name to the list. >> ")
new_email = input("Add a new email for that name. >> ")
combined = "\n" + new_name + ", " + new_email
directory.write(combined)
cont = input("Add more? Yes or No >> ")
if cont == "No" or cont == "no":
directory.close()
programactive = False
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.