It's not totally clear from the problem statement, but I think you are collecting data about a company (or many companies) and then you want to print that data out in a CSV file.
Firstly, a couple of issues with your existing code:
dic = [company_name, company_cve, "example", "another"] #dictionary
This is a list, not a dictionary. A dictionary has a key-value structure, and would be declared like this:
dic = { 'name': company_name, 'cve': company_cve, 'example': 'example data' }
Secondly, it's better to use with
when opening a file to forestall potential file opening errors:
with open('exampleCsv.csv', 'w') as csvfile:
# write to the file
Thirdly, if you use the existing csv
library, you don't have to worry about cases where (e.g.) company names or other file data has commas in it; csv
will handle that for you. See the csv
library documentation for full details. You will need to import the cvs
library at the start of your script:
import csv
import re
and create a csv.writer
object to output your data:
with open('exampleCsv.csv', 'w') as csvfile:
writer = csv.writer(csvfile, delimiter=',', quotechar='"') # set your CSV options here
Depending on what data structure you are using to hold the company data, you can print it out in different ways.
# list of headers
headers = [ 'company_name', 'company_cve', 'prop_1', 'prop_2' ]
# list of variables holding company data
dic = [ company_name, company_cve, example_1, example_2 ]
with open('exampleCsv.csv', 'w') as csvfile:
writer = csv.writer(csvfile, delimiter=',', quotechar='"')
writer.writerow( headers ) # print the header row
writer.writerow( dic )
Or if you created a dictionary containing your company data:
company = {
'company_name': 'Company A',
'company_cve': 'Some value',
'prop_1': 'value 1',
'prop_2': 'value 2'
}
# note that dictionary keys match the headers
headers = [ 'company_name', 'company_cve', 'prop_1', 'prop_2' ]
with open('exampleCsv.csv', 'w') as csvfile:
writer = csv.writer(csvfile, delimiter=',', quotechar='"')
writer.writerow( headers )
writer.writerow( map( lambda x: company[x], headers ) )
or a list of dictionaries for many companies:
company_data = [{
'company_name': 'Company A',
'company_cve': 'Some value',
'prop_1': 'value 1',
'prop_2': 'value 2'
},{
'company_name': 'Company B',
'company_cve': 'A different value',
'prop_1': 'value 3',
'prop_2': 'value 4'
}]
headers = [ 'company_name', 'company_cve', 'prop_1', 'prop_2' ]
with open('exampleCsv.csv', 'w') as csvfile:
writer = csv.writer(csvfile, delimiter=',', quotechar='"')
writer.writerow( headers )
for c in company_data:
writer.writerow( map( lambda x: c[x], headers ) )