write several txt to directory automatically

We have this if else iteration with the goal to split a dataframe into several dataframes. The result of this iteration will vary, so we will not know how much dataframes we will get out of a dataframe. We want to save that several dataframe as text (.txt):

txtDf = open('D:/My_directory/df0.txt', 'w')
txtDf.write(df0)
txtDf.close()

txtDf = open('D:/My_directory/df1.txt', 'w')
txtDf.write(df0)
txtDf.close()

txtDf = open('D:/My_directory/df2.txt', 'w')
txtDf.write(df0)
txtDf.close()

And so on ....

But, we want to save that several dataframes automatically, so that we don't need to write the code above for 100 times because of 100 splitted-dataframes.

This is the example our dataframe df:

column_df
237814
1249823
89176812
89634
976234
98634

and we would like to split the dataframe df to several df0, df1, df2 (notes: each column will be in their own dataframe, not in one dataframe):

column_df0   column_df1   column_df2
237814       89176812     976234
1249823      89634        98634

We tried this code:

import copy
import numpy as np
df= pd.DataFrame(df)
len(df)
if len(df) > 10:
   print('EXCEEEEEEEEEEEEEEEEEEEEDDD!!!')
   sys.exit()
elif len(df) > 2:
    df_dict = {}
    x=0
    y=2
    for df_letter in ['A','B','C','D','E','F']:
        df_name = f'df_{df_letter}'    
        df_dict[df_name] = copy.deepcopy(df_letter)
        df_dict[df_name] = pd.DataFrame(df[x:y]).to_string(header=False, index=False, index_names=False).split('\n ')
        df_dict[df_name] = [','.join(ele.split()) for ele in df_dict[df_name]]
        x += 2
        y += 2
    df_name
else:
    df
for df_ in df_dict:
    print(df_)
    print(f'length: {len(df_dict[df_])}')
    txtDf = open('D:/My_directory/{df_dict[df_]}.txt', 'w')
    txtDf.write(df)
    txtDf.close()

The problem with this code is that we cannot write several .txt files automatically, everything else works just fine. Can anybody figure it out?

Upvotes: 0

Views: 41

Answers (1)

effy
effy

Reputation: 181

If it is a list then you can iterate through it and save each element as string

import os
for key, value in df_dict.items():
    with open(f'D:/My_directory/{key}.txt', "w") as file:
        file.write('\n'.join(str(v) for v in value))

Upvotes: 1

Related Questions