以下功能是我未来计划的一部分,即图书馆计划。这个特殊的功能应该从文本文件中获取书籍,如果用户需要,那么"贷款"他们因此添加了一个字符串"(LOANED)"在这本书的作者之后。书籍首先按标题排序,然后是逗号和空格(,),然后是书籍的作者。我想要做的只是简单地添加一个"(贷款)"字符串在文本文件中的书的作者之后。然而,当我尝试这个时,(LOANED)字符串最终会在我想要的地方的另一条线(下面一行)上结束,并且它让我疯狂。
def lend_book(title):
f = open("booksbytitle.txt", "r+")
d={}
#splits the registry up into a dictionary with the book title as key and the book author as value to that key
for i in f:
x=i.split(",")
a=x[0]
b=x[1]
d[a]=b[0:(len(b))]
#checks if the title is in the dictionary, else skips down and quits the function
if title in d:
print("\n", title, "is available in the library and is written by"+d[title])
saved_author = d[title][1:]
while True:
alternative=input("Do you want to lend this book? [y/n] ")
if alternative.lower() == "y":
print("The book is now loaned ")
break
elif alternative.lower() == "n":
print("Okay, going back to main menu.. ")
break
else:
print("That is not a valid choice. Type 'y' or 'n'")
f.close()
loaned="(LOANED)"
f=open("booksbytitle.txt", "r+")
z=f.readlines()
f.seek(0)
for i in z:
if title not in i:
f.write(i)
f.write("\n" + title + ", " + saved_author + loaned)
f.truncate()
f.close()
#clears the program of unintented blank lines
fh = open("booksbytitle.txt", "r")
lines = fh.readlines()
fh.close()
keep = []
for line in lines:
if not line.isspace():
keep.append(line)
fh = open("booksbytitle.txt", "w")
fh.write("".join(keep))
fh.close()
else:
print("There wasnt a book by that name found in the registry")
答案 0 :(得分:2)
很难说出搞乱的格式和无意义的单字母变量名称,但我怀疑问题是这样的:
当您迭代某个文件的行时,例如for i in f:
,每个文件都以换行符('\n'
)结束。
当你split(",")
时,最后一个分割字符串仍然包含该换行符。
所以最终,当你尝试将该字符串粘贴在字符串的中间时,它在结尾处有一个换行符,这意味着你最终会在字符串的中间添加换行符。
要解决此问题,请在阅读每行时使用rstrip
:
for i in f:
x = i.rstrip().split(",")
这可能意味着您现在在输出中缺少换行符。你期望免费获得它们,但现在你不能。所以你可能需要这样做:
f.write("\n" + title + ", " + saved_author + loaned + "\n")
然而,也许不是。我注意到由于某种原因你在每行的开始放置一个"\n"
,所以这可能只是意味着你最终会在每一行之间留下额外的空白行(以及文件开头的额外空白行,这是使用"\n" +
)时所固有的。
答案 1 :(得分:1)
你可以在字符串上使用rstrip()来删除正确的空格(换行符), 然后加入“\ n”而不是空字符串。
PS:顺便说一下,你可以更简单地编写一些代码。例如,您可以一次性获取文件中的所有行,同时过滤掉空行和rstrip,如下所示:
with open(filename, "r") as handler:
keep = [line.rstrip() for line in handler if line]
('with'负责在缩进块之后自动关闭文件,然后是列表解析,并且打开文件对象“handler”在迭代时为你提供行。)