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.
When you open a CSV file in Excel, the program will automatically detect any empty cells and treat them as if they were filled with the value 0. This can cause problems if you are expecting to see blank cells in your data. There are a few ways to work around this issue.
You can add an empty column to the pandas dataframe using the = operator and assign null values to the column. What is this? An empty column will be added at the end of the dataframe with the column header Empty_Column.
There are multiple ways to add a new empty/blank column (single or multiple columns) to a pandas DataFrame by using assign operator, assign() , insert() and apply() methods. By using these you can add one or multiple empty columns with either NaN , None , Blank or Empty string values to all cells.
You can insert blank "columns" in a csv simply by writing None
or 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 will correctly include the extra commas as required for your blank columns, including a trailing comma if required.
If you use a DictWriter 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'}
write.writerow(row) # Automatically skips missing keys
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With