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


在我的

代码中,它会询问您的名字是什么,如果您的名字在文件中,则说欢迎回来,如果他们的名字不在文件中,则询问他们是否希望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()

让我们来看看一些改进。由于你使用raw_input()我将假设Python 2.x:

def AI():
    # you can use r'' to specify a raw string and avoid using '\' to escape ''
    fpath = r'\ph-fss1StudentsS39055Desktopnames.txt'
    # this is called a 'context manager'
    # when you are done with your operations, the file will close automatically
    # the 'r+' mode opens for reading and writing
    with open(fpath, 'r+') as f:
        # this is list comprehension and I assume each name is on a new line
        # a set is a container for unique values
        # assuming that you will not have multiple of the same names
        # if so, how do you plan to account for them?
        names = set([line for line in f])
        print "Hello and welcome to the Creative, Orginal, Reactive, A.I, Cora."
        name = raw_input("What is your name? ")
        if name in names:
            print "Welcome back " + name
        else:
            print "You are a new user, would you like to me to remember your name?"
            # this is fine, but what happens I just put in 'y' or 'n'?
            # look for methods to handle invalid input
            choice = raw_input("Yes/No: ").lower()
            if choice == "yes":
                # because we opened the file in 'r+', we seek(0) which puts us at the top
                # then when we writelines(list(names)) we overwrite the entire file
                # and store the original data with the new name as well
                file.seek(0)
                names.add(name)
                # writelines() just writes an iterable versus a string
                file.writelines(list(names))

您必须在此处做出一些设计选择。但是,如果您有任何问题,请询问。

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

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)

最新更新