繁体   English   中英

Python不会读取文本文件

[英]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) 您的ReadAddNo条件逻辑没有正确检查这两个条件。 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM