NamAshena
NamAshena

Reputation: 1737

writing pandas df to file using variable as file name

I am trying to write pandas df to an output file with:

outFileName="myfile_" + gene_name #gene_name gets a new value from argparse 

df.to_csv('%.csv' %outFileName, sep=',', index=False)

the error I am getting::

TypeError: %c requires int or char

I tried

outFileName=str("myfile_" + gene_name)

and got the same error. Am I missing something? I can save the df if I do not use variable as outputfile name but I need to have the variable.

Upvotes: 5

Views: 15025

Answers (3)

user3265950
user3265950

Reputation: 11

name = x
nameFile = name +'.csv'

with open(nameFile, "a") as a_file:
    a_file.write(data)

Upvotes: 1

Ramineni Ravi Teja
Ramineni Ravi Teja

Reputation: 3906

Use to_csv:

df.to_csv(outFileName+".csv", sep=',', index=False)

Upvotes: 5

jezrael
jezrael

Reputation: 862661

I think you can use format for new name for file:

df.to_csv('myfile_{}.csv'.format(gene_name), sep=',', index=False)

Or if use python 3.5+ is possible use f-strings:

df.to_csv(f'myfile_{gene_name}.csv', sep=',', index=False)

Upvotes: 1

Related Questions