嗨,将字符串附加到文件中时,我遇到了一个小问题。因此,基本上,我使用以下方法添加文件中不存在的书:
def writeBooks2File(booklist_dir):
BOOKS = ['Human Philosophy', 'Human Philosophy book']
for val in BOOKS:
if val not in open(booklist_dir, "r").read():
f = open(booklist_dir, "a")
f.write(val + "\n")
f.close()
我的文件包含以下内容:
Human Philosophy
Human Philosophy book
可以说我删除了Human Philosophy
,该文件仅包含Human Philosophy book
。再次运行writeBooks2File(booklist_dir)
不会返回以下输出:
Human Philosophy
Human Philosophy book
但是请返回此值:
Human Philosophy book
我需要怎么做才能将Human Philosophy
添加到文件中,并且两个值彼此相似。
答案 0 :(得分:1)
问题是
>>> 'Human Philosophy' in 'Human Philosophy book\n'
True
因此,您可以执行以下操作:
>>> ('Human Philosophy'+'\n') in 'Human Philosophy book\n'
False
我重写了您的脚本...应该可以更好地使用
def writeBooks2File(booklist_dir,books):
f = open(booklist_dir, "a")
for val in books:
if val+'\n' not in open(booklist_dir, "r").read():
f.write(val + "\n")
f.close()
def removebooks(booklist_dir,books):
with open(booklist_dir, "r") as File:
all_books = File.read()
for book in books:
new = all_books.replace(book+'\n','')
with open(booklist_dir, "w") as File:
File.write(new)
books = ['Human Philosophy book','Human Philosophy']
writeBooks2File('test.txt',books)
remove_books = ['Human Philosophy']
removebooks('test.txt',remove_books)
通过此操作,您可以执行无法执行的操作。即使有“人类哲学书”,也要在文件中附加“人类哲学”