Amanda_C
Amanda_C

Reputation: 39

How to remove newlines from csv files?

How can I remove the newlines from my csv file? This is what my current output looks like: {'\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')}

and this is what the output is suppose to look like:

{'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')}

I don't want to use any of the in built csv tools or whatever because we haven't done those in class so I doubt we'd need to use them in these questions.

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

Upvotes: 0

Views: 82

Answers (2)

roganjosh
roganjosh

Reputation: 13175

With minimal modifications of your code:

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

Empty strings are falsey, so this will not add to your library dict if the first entry of a row is blank.

Upvotes: 1

Ollie
Ollie

Reputation: 1702

Ignore the first line by adding next(file) before your for loop, and call .strip() on the ISBN.

Upvotes: 0

Related Questions