Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-向txt文件添加唯一的电视字符_Python_List - Fatal编程技术网

Python-向txt文件添加唯一的电视字符

Python-向txt文件添加唯一的电视字符,python,list,Python,List,Mynames.txt包含以下字符名: Peter Lois Meg Chris 但缺少以下字符: Chris Stewie Bryan 如何将这些名称附加到names.txt文件中?我还需要确保列表中只添加了唯一的名称(如果文件中已经存在该名称,请返回“此名称已输入”)。我试图逐行扫描文件,以决定是否附加名称(如果文件中不存在)或返回“此名称已输入” 以下是我到目前为止的情况: user = input('Input character name:') wi

My
names.txt
包含以下字符名:

Peter  
Lois  
Meg   
Chris  
但缺少以下字符:

Chris  
Stewie  
Bryan  
如何将这些名称附加到
names.txt
文件中?我还需要确保列表中只添加了唯一的名称(如果文件中已经存在该名称,请返回“此名称已输入”)。我试图逐行扫描文件,以决定是否附加名称(如果文件中不存在)或返回“此名称已输入”

以下是我到目前为止的情况:

user = input('Input character name:')

with open('names.txt','r') as characters:
    characters.readline()

for names in characters:
    names=names.strip

if names = user
    print ('This name is already inputted')
else:
    user.append()

知道如何让代码正常工作吗?

我不知道您想做什么。但你可能想这样做

user = raw_input('Input character name:').strip()

with open('names.txt','r') as fp:
   names = [line.strip() for line in fp.readlines()]

if user in names:
    print ('This name is already inputted')
else:
    with open('names.txt', 'a') as fp:
        fp.write('\n' + user)

“UnicodeDecodeError:'ascii'编解码器无法解码第25位的字节0xa9:序号不在范围内(128)”谢谢,它实际上可以工作。您知道如何将新名称附加到else语句中的txt文件中吗?而且,这只会查看第一行,不会扫描每一行。@Maverick:I更新为将用户附加到文件中<代码>这只查看第一行,它不会扫描每行。否,它会检查用户是否唯一<代码>如果用户名为:请执行此操作。