我无法让我的代码打开我的.txt文件并读取它是否有名称

时间:2017-10-20 19:32:55

标签: python

在我的代码中,它询问你的名字是什么,如果你的名字在文件中,那么如果他们的名字不在其中,请说欢迎他们的名字然后询问他们是否想让Cora记住它,如果是的话然后写他们的将名称命名为文件。

def AI():
    names = open("\\\\ph-fss1\\Students\\S39055\\Desktop\\names.txt","w")
    name = raw_input("Hello and welcome to the Creative, Orginal, Reactive, A.I, Cora. What is your name? ")
    file.read(names)
    if name in names:
        print "Welcome back " + name
    if name not in names:
      print "You are a new user would you like to me to remember your name?"
      name_yes = raw_input("Yes/No: ").lower()
      if name_yes == "yes":
          file.wright(name)
          file.close()

2 个答案:

答案 0 :(得分:1)

问题是您从未实际读取过该文件的内容,以便检查该名称是否存在。试试这个:

name = raw_input("Hello and welcome to the Creative, Orginal, Reactive, A.I, Cora. What is your name? ")

if name in open("\\\\ph-fss1\\Students\\S39055\\Desktop\\names.txt").read():
     print "Welcome back " + name
else:
  print "You are a new user would you like to me to remember your name?"
  name_yes = raw_input("Yes/No: ").lower()
  if name_yes == "yes":
      with open("\\\\ph-fss1\\Students\\S39055\\Desktop\\names.txt", "a") as myfile:
          myfile.write(name)

答案 1 :(得分:1)

让我们来看看一些改进。由于您使用int i = -1; while ((i = br.read()) != -1) { char c = (char)i; for (int i = 0; i <= size; ++i) { if (size == 0) { characters[i] = c; charCount[i]++; size++; System.out.println("Letter/Count: " + characters[i] + "/" + charCount[i]); break; } if (characters[i] == c) { charCount[i]++; break; } else if (i == size) { characters[i] = c; charCount[i]++; size++; System.out.println("Letter/Count: " + characters[i] + "/" + charCount[i]); break; } } } 我将假设Python 2.x:

raw_input()

您必须在此处进行一些设计选择。但如果您有任何疑问,请随时提出。