Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

python - 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 someone suggest me the best-optimized way to do that in Python and Pandas?

After I fill the row the csv file should look like:

 cat mycsv.csv
 col_1 , col_2 , col_3 , col_3
 0@@@None@@@None@@@None

How to insert index and separator is @@@ instead of , ? I am getting an error as:

tmp.to_csv(csvFile,sep='@@@',index=True) 
 , line 1381, in to_csv
formatter.save()
 3.6.1/linux_x86_64/lib/python3.6/site-packages/pandas/formats/format.py", line 1473, in save
self.writer = csv.writer(f, **writer_kwargs)
  TypeError: "delimiter" must be a 1-character string
Exception ignored in: <module 'threading' from Traceback (most recent call last):
File python-3.6.1/linux_x86_64/lib/python3.6/threading.py", line 1015, in 
_delete
del _active[get_ident()] 
KeyError: 140459817715712
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 + "
" + "@@@".join(["None"] * len(tmp.split(',')))
with open("mycsv.csv","w") as f1:
    f1.write(tmp)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...