How to use the writerow function in Python

Viewed 521

Im using csv to write rows to an empty text file, but when I open the textfile I see there is a space between each letter/character. I have no idea what I'm doing wrong.

This is my code:

import csv
import configparser

# Read local `config.ini` file.
config = configparser.ConfigParser()                                     
config.read(r'C:\data\FF\Desktop\Studio\cfg.ini')

header_1= config['HEADERS']['headers_1']
header_2 =config['HEADERS']['headers_2']

full_path = r'C:\data\FF\Desktop\Studio\New Text Document.txt' 

with open(full_path, 'w') as output:
    writer = csv.writer(output, delimiter = '\t')
    writer.writerow(header_1)
    writer.writerow(header_2)

This is how cfg.ini looks like:

[HEADERS]
headers_2 = ['VEHICLE', 'MODEL', 'DSG', 'YEAR', 'MONTH', 'DAY', 'HOUR', 'MINUTE','SECOND']

headers_1 = ['*****data*****']

This is how New Text Document.txt looks like: enter image description here

1 Answers

The problem is not the csv.writerow, but how you read the list from cfg.ini. You read string, not list (as you think). Check Lists in ConfigParser And to fix the extra blank line (when using csv module on windows) you need to specify newline='' - check CSV file written with Python has blank lines between each row

cfg.ini

[HEADERS]
headers_2 = ["VEHICLE", "MODEL", "DSG", "YEAR", "MONTH", "DAY", "HOUR", "MINUTE","SECOND"]
headers_1 = ["*****data*****"]

your file:

import csv
import configparser
import json

# Read local `config.ini` file.
config = configparser.ConfigParser()                                     
config.read(r'C:\data\FF\Desktop\Studio\cfg.ini')

header_1 = json.loads(config['HEADERS']['headers_1'])
header_2 = json.loads(config['HEADERS']['headers_2'])

full_path = r'C:\data\FF\Desktop\Studio\New Text Document.txt' 

with open(full_path, 'w', newline='') as output:
    writer = csv.writer(output, delimiter = '\t')
    writer.writerow(header_1)
    writer.writerow(header_2)
Related