Hello I have a database that i am trying to make a .csv file quickly from.
my data looks like this.
Song_Name,File_Name,Artist_Name,Artist_ID
Song1,filename1,artistname,artist001
Song1,filename1,artistname,artist001
Song1,filename1,artistname,artist001
Song1,filename1,artistname,artist001
and this is how I need it to look.
Song_Name,,File_Name,Artist_Name,,Artist_ID
Song1,,filename1,artistname,,artist001
Song1,,filename1,artistname,,artist001
Song1,,filename1,artistname,,artist001
Song1,,filename1,artistname,,artist001
what would be the best way to do this. thank you.
You can insert blank "columns" in a CSV file simply by writing None
or an empty string ''
.
For example:
with open('songs.csv', 'w', newline='') as f:writer = csv.writer(f)writer.writerow(['Song_Name', None, 'File_Name', 'Artist_Name', None, 'Artist_ID']) # Write headers# Now you iterate over your data:for row in data:writer.writerow([row['song_name'], None, row['file_name'], ...])
Your CSV file will correctly include the extra commas as required for your blank columns, including a trailing comma if required.
If you use a DictWriter
, then it's even easier. You simply don't populate the dictionary with the keys you want to leave out:
with open('songs.csv', 'w', newline='') as f:headers = ['Song_Name', None, 'File_Name', ...]writer = csv.DictWriter(f, fieldnames=headers)writer.writeheader()# Now write a sample row:row = {'Song_Name': 'Dumb', 'Artist_Name': 'Nirvana'}writer.writerow(row) # Automatically skips missing keys