rafvasq
rafvasq

Reputation: 1522

Newlines in CSV data - Python

The following block of code is my attempt at making a CSV filled with data about employees but I've noticed that newlines characters at the end of the last header and its respective data are messing with my searches in the data.

I've tried to use 'ab' instead of 'a' but I get a Type error asking for a bytes-type object and not a str type.

def write_csv(emp_json, licenseName):
    filePath='C:\Scripts\Python\data.csv'
    data = open(filePath, 'a') 
    csvwriter = csv.writer(data)
    count = 0
    for emp in emp_json:
        emp.update({'licenseName':licenseName})
        if count == 0:
            header = emp.keys()
            csvwriter.writerow(header)
            count += 1
        csvwriter.writerow(emp.values())
    data.close()

Any info on how to remove all newline characters from the headers and the data? Or how to create the data without newlines in the first place? Please comment if you need more information and context.

Thanks

Upvotes: 0

Views: 929

Answers (1)

Mohamed Ali JAMAOUI
Mohamed Ali JAMAOUI

Reputation: 14689

If want no newlines, add newline="" as parameter to open(...):

def write_csv(emp_json, licenseName):
    filePath='C:\Scripts\Python\data.csv'
    with open(filePath, 'a', newline="") as data: 
       csvwriter = csv.writer(data)
       count = 0
       for emp in emp_json:
           emp.update({'licenseName':licenseName})
           if count == 0:
               header = emp.keys()
               csvwriter.writerow(header)
               count += 1
           csvwriter.writerow(emp.values())

PS: use with open(..) for writing to csv it takes care of opening and closing the file for you.

Upvotes: 1

Related Questions