Python: Creating Multiple Text file from a column in CSV file

Viewed 452

I have a CSV file with 3 columns Imagename , image_size and class. I want to create multiple text files reading the CSV with Imagename as filename and image_size and class as file content.

I need to loop through the Imagename and if the Imagename is similar the append the corresponding image_size and class in a single txt file.

If the Imagename is different, create another txt file and append it's corresponding image_size, class.

Below is the sample csv:

Image_name   image_size  class
Img_0001     150         brightness 
Img_0001     153         Noise
Img_0001     170         skewness
Img_0002     132         brightness
Img_0002     188         Noise
Img_0002     191         skewness
Img_0003     159         brightness
Img_0003     111         Noise
Img_0003     170         skewness

The filename I need to create:

Img_0001.txt 

and the file content within the txt file :

150         brightness 
153         Noise
170         skewnes
2 Answers

After reading your CSV file with pd.read_csv you can create txt files for each unique Image_name entry in the following way.

for image in df.Image_name.unique():
    fileName = image +".txt"
    file = open(fileName,"w+") #creating a txt file if not already exists
    
    #adding rows for each unique image name 
    for row in df[df.Image_name==image].values:
        file.write(f"{row[1]} {row[2]}") #writing to txt file

Here df.Image_name.unique() returns all unique values under Image_name column. Then we runs loop for each name and retrieve info from the CSV and add those to txt files.

You can read the CSV file with pd.read_csv and then use .groupby() to "split" the dataframe to multiple dataframes according the Image_name. For example:

df = pd.read_csv("your_file.csv")

for filename, g in df.groupby("Image_name"):
    g.to_csv(filename + ".txt", index=False)

Creates Img_000*.txt files.

Related