k0ngcrete
k0ngcrete

Reputation: 116

Write .csv file from pandas dataframe with consecutive spaces as delimiter

I want to write a text file which is separated by four spaces instead of one tab:

df.to_csv(file,sep= '\s\s\s\s') 

instead of

df.to_csv(file,sep= '\t')

I tried regex :

df.to_csv(file,sep= r'\s{4}') 

which did not work either ?

Is this doable without writing and the replacing the delimiter?

Upvotes: 2

Views: 4501

Answers (1)

zipa
zipa

Reputation: 27869

This could be a workaround:

myCsv = df.astype(str).apply(lambda x: '   '.join(x), axis=1)
myCsv.rename('   '.join(df.columns)).to_csv(file, header=True, index=False)

Upvotes: 2

Related Questions