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

2024-04-29 21:30:13 发布

您现在位置:Python中文网/ 问答频道 /正文

如何从csv文件中删除换行符?我的电流输出是这样的: {'\n': ('', ''), '0-586-08997-7\n': ('Kurt Vonnegut', 'Breakfast of Champions'), '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', 'Breakfast of Champions'), '978-0-14-302089-9': ('Lloyd Jones', 'Mister Pip'), '1-877270-02-4': ('Joe Bennett', 'So Help me Dog'), '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"))

Tags: pipofcsvforlinelibraryjoebennett
2条回答

只需对代码进行最少的修改:

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"))

空字符串是false,因此如果行的第一个条目是空的,则这不会添加到librarydict中。你知道吗

忽略第一行,在for循环之前添加next(file),并调用ISBN上的.strip()。你知道吗

相关问题 更多 >