如何为文件添加一个名称(如果它尚不存在)?
问题描述:
我有一个包含名称列表的文件,每行一个名称。如何为文件添加一个名称(如果它尚不存在)?
我想检查文件中是否存在名称。如果没有,我想将它附加在文件的末尾。
names.txt中
Ben
Junha
Nigel
这里是我试图做的:
name=raw_input(" Name: ")
with open("names.txt") as fhand:
if name in fhand:
print "The name has already been in there"
else:
with open("file.txt","a+") as fhand:
fhand.write(name)
但现有的名称是从来没有发现,而名称我输入总是得到追加到最后一行。
答
你的总体想法很好,但有一些细节是关闭的。
与其打开文件两次,一次处于读取模式,然后是追加模式,您可以在读取/写入(r+
)模式下打开一次。
open()
返回文件对象,而不是文本。所以你不能只用if some_text in open(f)
。您必须阅读文件。
由于您的数据是逐行构建的,因此最简单的解决方案是使用for
循环,该循环将迭代文件的各行。
您不能使用if name in line
,因为"Ben" in "Benjamin"
将是True
。你必须检查名称是否相同。
所以,你可以使用:
name=raw_input(" Name: ")
# With Python 3, use input instead of raw_input
with open('names.txt', 'r+') as f:
# f is a file object, not text.
# The for loop iterates on its lines
for line in f:
# the line ends with a newline (\n),
# we must strip it before comparing
if name == line.strip():
print("The name is already in the file")
# we exit the for loop
break
else:
# if the for loop was exhausted, i.e. we reached the end,
# not exiting with a break, this else clause will execute.
# We are at the end of the file, so we can write the new
# name (followed by a newline) right where we are.
f.write(name + '\n')
看起来你要我们写一些代码给你。尽管许多用户愿意为遇险的编码人员编写代码,但他们通常只在海报已尝试自行解决问题时才提供帮助。证明这一努力的一个好方法是包含迄今为止编写的代码,示例输入(如果有的话),期望的输出以及实际获得的输出(控制台输出,回溯等)。您提供的细节越多,您可能会收到的答案就越多。检查[常见问题]和[问] – Skam
可能的重复https://stackoverflow.com/questions/4940032/search-for-string-in-txt-file-python。 –