Python 3;写入文本文件,无意换行(初学者)

Python 3;写入文本文件,无意换行(初学者),python,Python,下面的函数是我未来程序的一部分,一个库程序。这个特殊的函数应该是从文本文件中获取书籍,如果用户愿意,“借出”它们,从而在书籍作者之后添加一个字符串(“借出”)。这些书首先按标题排序,然后是逗号和空格(,),然后是书的作者。我想做的只是,简单地说,在文本文件中书的作者之后添加一个“(LOANED)”字符串。然而,当我尝试这一点时,(借来的)字符串只是在一个不同的行(下面一行)结束,从我想要的地方,它让我发疯 def lend_book(title): f = open("booksbyti

下面的函数是我未来程序的一部分,一个库程序。这个特殊的函数应该是从文本文件中获取书籍,如果用户愿意,“借出”它们,从而在书籍作者之后添加一个字符串(“借出”)。这些书首先按标题排序,然后是逗号和空格(,),然后是书的作者。我想做的只是,简单地说,在文本文件中书的作者之后添加一个“(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")

糟糕的格式和毫无意义的单字母变量名很难分辨,但我怀疑问题在于:

当您迭代文件的行时,如f:中i的
,每行都以换行符(
'\n'
)结尾

当您
拆分(“,”)
每个字符串时,最后一个拆分的字符串仍然包含该换行符

<>最后,当你试图把字符串放在一个字符串的中间时,在结尾有一个换行符,这意味着你在字符串中间有一个换行符。

要解决此问题,请在阅读时在每行上使用
rstrip

for i in f:
    x = i.rstrip().split(",")
这可能意味着您现在在文件的输出中缺少换行符。你本想免费得到它们,但现在你没有了。因此,您可能必须执行以下操作:

f.write("\n" + title + ", " + saved_author + loaned + "\n")
with open(filename, "r") as handler:
  keep = [line.rstrip() for line in handler if line]
然而,也许不是。我注意到,出于某种原因,您在每一行的开头都添加了一个
“\n”
,因此这可能意味着您在每一行之间都会有额外的空行(以及文件开头的额外空行,这是使用
“\n”+
)所固有的)。

您可以在字符串上使用rstrip()来删除正确的空格(新行), 然后将“\n”而不是空字符串连接起来

PS:顺便说一下,您可以编写一些更简单的代码。例如,您可以一次获取文件中的所有行,过滤掉空行,然后同时rstrip所有行,如下所示:

f.write("\n" + title + ", " + saved_author + loaned + "\n")
with open(filename, "r") as handler:
  keep = [line.rstrip() for line in handler if line]

(with负责在缩进块之后自动关闭文件,然后有一个列表理解,打开的文件对象“handler”在迭代时为您提供行。)

我不确定问题到底是什么,但每行末尾都会出现一个
\n
字符。如果不需要周围的空格,只需执行一个
line=line.strip()
。请为变量使用有意义的名称。这
a
b
f
i
x
z
等内容很难阅读。此外,[WriteFile]标记用于
NSData
和相关类上的Cocoa
writeToFile:
方法。除非您使用PyObjC创建
NSData
对象并对其调用方法,否则不应将其用于Python问题。行
d[a]=b[0:(len(b))
可以重构(更改)为
d[a]=b