Python 如何从csv文件中删除换行符?

Python 如何从csv文件中删除换行符?,python,Python,如何从csv文件中删除换行符?这就是我当前输出的样子: {'\n':,'0-586-08997-7\n':'Kurt Vonnegut','冠军早餐','978-0-14-302089-9\n':'Lloyd Jones','Mister Pip','1-877270-02-4\n':'Joe Bennett','So Help me Dog','0-812-55075-7':'Orson Scott Card','Speaker for the Dead' 这就是输出的样子: {'0-586

如何从csv文件中删除换行符?这就是我当前输出的样子: {'\n':,'0-586-08997-7\n':'Kurt Vonnegut','冠军早餐','978-0-14-302089-9\n':'Lloyd Jones','Mister Pip','1-877270-02-4\n':'Joe Bennett','So Help me Dog','0-812-55075-7':'Orson Scott Card','Speaker for the Dead'

这就是输出的样子:

{'0-586-08997-7':'Kurt Vonnegut','冠军早餐', ‘978-0-14-302089-9’:‘劳埃德·琼斯’、‘皮普先生’, “1-877270-02-4”:“乔·贝内特”,“帮帮我,狗”, '0-812-55075-7':'Orson Scott Card','Speaker for the Dead'}

我不想使用任何内置的csv工具或任何东西,因为我们在课堂上没有做过这些,所以我怀疑我们是否需要在这些问题中使用它们

def isbn_dictionary(filename):
    """docstring"""
    file = open(filename, "r")
    library = {}


    for line in file:
        line = line.split(",")
        tup = (line[0], line[1])

        library[line[2]] = tup
    return library


print(isbn_dictionary("books.csv"))

通过在for循环之前添加nextfile忽略第一行,并在ISBN上调用.strip。

只需对代码进行最小修改:

def isbn_dictionary(filename):
    """docstring"""
    file = open(filename, "r")
    library = {}


    for line in file:
        line = line.split(",")
        if line[0]: # Only append if there is a value in the first column
            tup = (line[0], line[1])

            library[line[2].strip()] = tup # get rid of newlines in the key
    file.close() # It's good practice to always close the file when done. Normally you'd use "with" for handling files.
    return library


print(isbn_dictionary("books.csv"))

空字符串为假,因此如果行的第一个条目为空,则不会将其添加到库dict中。

为行。替换\n,选项?如果我这样做,我将在开始时获取以下内容:,但字典中的其余\n将消失。我们得到了一个csv文件以转换为字典,每行的第一个值将作为键,然后剩余值将作为这些键的值如何忽略第一行?