Home > Software engineering >  How to save a name as a variable when saving a Data frame file?
How to save a name as a variable when saving a Data frame file?

Time:02-11

I have to save several files at a time.

It is saved as .txt using .to_csv.

The following method is used to save the Data Frames of position, energy, number, event, and height.

position.to_csv('/HDD1/abc_position.txt',index=False,sep=" ")
energy.to_csv('/HDD1/abc_energy.txt',index=False,sep=" ")
number.to_csv('/HDD1/abc_energy.txt',index=False,sep=" ")
event.to_csv('/HDD1/abc_event.txt',index=False,sep=" ")
height.to_csv('/HDD1/abc_height.txt',index=False,sep=" ")

Let's check the save file name above. They contain 'abc'. I want to replace 'abc' with the variable 'A = abc' without having to write it down many times.

In other words, it should be as follows.

A = abc
postion.to_csv('/HDD1/A_position.txt',index=False,sep=" ")
energy.to_csv('/HDD1/A_energy.txt',index=False,sep=" ")
number.to_csv('/HDD1/A_energy.txt',index=False,sep=" ")
event.to_csv('/HDD1/A_event.txt',index=False,sep=" ")
height.to_csv('/HDD1/A_height.txt',index=False,sep=" ")

Is there a way to save files using variables as above?

CodePudding user response:

Are you looking for f-strings?

A = 'abc'
postion.to_csv(f'/HDD1/{A}_position.txt',index=False,sep=" ")
energy.to_csv(f'/HDD1/{A}_energy.txt',index=False,sep=" ")
number.to_csv(f'/HDD1/{A}_energy.txt',index=False,sep=" ")
event.to_csv(f'/HDD1/{A}_event.txt',index=False,sep=" ")
height.to_csv(f'/HDD1/{A}_height.txt',index=False,sep=" ")

CodePudding user response:

can use an f-string. Let

A = 'abc'

postion.to_csv(f'/HDD1/{A}_position.txt',index=False,sep=" ")
energy.to_csv(f'/HDD1/{A}_energy.txt',index=False,sep=" ")
number.to_csv(f'/HDD1/{A}_number.txt',index=False,sep=" ")
event.to_csv(f'/HDD1/{A}_event.txt',index=False,sep=" ")
height.to_csv(f'/HDD1/{A}_height.txt',index=False,sep=" ")


EDIT Aditional (don't know if pythonic) you can create dictionary with all your dataFrames and call this a simplier way:

dataFrames = {'position':position,
              'energy':energy,
              'number':number,
              'event':event,
              'height':height 
             }

A = 'abc'
dir = '/HHD1'

for key,val in dataFrames.items():
    val.to_csv(f'{dir}/{a}_{key}.txt',index=False,sep=" ")

The last one liner is the same as:

[val.to_csv(f'{dir}/{a}_{key}.txt',index=False,sep=" ") for key, val in dataFrames.items()]

I think the first way is more pythonic, but not sure

  • Related