How To Write A Single Row Cell By Cell And Fill It In Csv File
I have a CSV file that only has column headers:  cat mycsv.csv  col_1@@@col_2@@@col_3@@@col_3  I have to fill a single row with None values in each cell of the CSV file. Can someon
Solution 1:
Does it a @ or , ? If you using a formal csv file, the separator of the header should be the same as the contents.
If you mean ,, you could use something like that.
import pandas as pd
# just for abrevation
tmp = pd.read_csv("mycsv.csv",sep=',')
tmp.loc[0,:] = "None"
tmp.to_csv("mycsv.csv",sep=',',index=False)
If you mean @, I suggest that you should not use pandas. Just using the simply IO ways.
tmp = open("mycsv.csv","r").read()
tmp = tmp + "\n" + "@@@".join(["None"] * len(tmp.split(',')))
with open("mycsv.csv","w") as f1:
    f1.write(tmp)
Solution 2:
What you are trying to do is rather non-standard. First read the the first line in as the header and split it using your @@@ delimiter. Next open an output file and write this header using , as a delimiter. Next write your row using the @@@ delimiter. For example:
row = [0, None, None, None]
withopen('mycsv.csv') as f_input:
    header = next(f_input).strip().split('@@@')
withopen('mycsv2.csv', 'w') as f_output:
    f_output.write(' , '.join(header) + '\n')
    f_output.write('@@@'.join(map(str, row)) + '\n')
If mycsv.csv contains:
col_1@@@col_2@@@col_3@@@col_3        
Then mycsv2.csv would be written as:
col_1 , col_2 , col_3 , col_3
0@@@None@@@None@@@None
Post a Comment for "How To Write A Single Row Cell By Cell And Fill It In Csv File"