Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python adding a blank/empty column. csv

Tags:

python

csv

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.

like image 647
chris mayer Avatar asked Oct 29 '14 02:10

chris mayer


People also ask

Can CSV have empty columns?

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.

How do you append an empty column to a Dataframe in Python?

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.

How do you add multiple empty columns in a data frame?

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.


1 Answers

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
like image 158
supermitch Avatar answered Oct 25 '22 17:10

supermitch