0

I'm working with a lot of different files and after I am done editing I want to save it as a new csv file.

print(files[0])
mhofmanmusselsT1_1L.raw

# I want the csv file for this dataset to be namend waves_T1_1L.csv, 
# but if I select a files[3] it would be waves_T3_2S.csv

t = files[0]
testtype = t[14:19]
name= ("waves_"+testtype)

Using the to_csv code it uses the df name as the file name. I'am quite new to python so it might be something obvious but is there a way to use

print(name)
waves_T1_1L

name = pd.DataFrame(df)
#Where name would function like if "print(name)" would be used,
#so it will automatically update if a different "files[n]" would be used.
#Unfortunately it won't allow me to do that.

UPDATE I have figured it out it took more steps than I expected.

Name = files[0]
testtype = Name[14:19]
filename = "waves_"+ testtype
wavedata.to_csv('out.csv')
old_name= r"workdirectory/out.csv"
new_name= r"workdirectory"+filename+".csv"
os.rename(old_name,new_name)

The output file will be changed from out.csv to waves_T1_1L.csv and it is updated if a different file is selected as input.

MHofman
  • 51
  • 6
  • Does this answer your question? [How can you dynamically create variables?](https://stackoverflow.com/questions/5036700/how-can-you-dynamically-create-variables) – Ynjxsjmh Apr 19 '22 at 15:38
  • @Ynjxsjmh not really, I have a hard time clearly describing the problem, since I'm quite new to all this. When I select a different file the "testtype" will change into a T2_3S for example and since i will have to go over a couple hundred of files i was hoping that there is a way to do this automatically. In the same way that the by changing the "files[0]" to "files[3]" would automatically change the outcome of testtype i want it to automatically change the name aspect. I will also update the question – MHofman Apr 19 '22 at 16:54

1 Answers1

1

The first argument of pandas.DataFrame.to_csv will save it to the filename you specify.

df.to_csv('NewName.csv')

If you want to save it to a new folder, you have to use the os library

import os  
os.makedirs('folder/subfolder', exist_ok=True)  
df.to_csv('folder/subfolder/out.csv')

Relevant Documentation: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_csv.html

NickP
  • 66
  • 4
  • It is not the to_csv part I am struggling with. In this case the file would be called "out.csv" and i want it to change the "out" part automatically to the value of the variable name, which changes from dataframe to dataframe. – MHofman Apr 19 '22 at 17:14