Search code examples
pythoncsvfilereaderwriter

write text file into csv file in python


I'm trying to write a text file into csv file using csv package in python using this code:

import csv

with open(r'C:\Users\soso-\Desktop\SVM\DataSet\drug_list.txt') as f:
    with open('integrated_x.csv', 'w') as out_file:
        writer= csv.writer(out_file)
        for line in f:
            print(line.strip())
            writer.writerow(line.strip())

enter image description here

I expected the the file to be as in terminal, but I dont know why it written in the csv file like this

how can I fix it the data appears in csv like this :

D,B,0,0,6,3,2

D,B,0,0,4,3,3

D,B,0,1,1,9,4

D,B,0,0,2,7,3

D,B,0,2,5,3,0

I want the csv file to be like this :

DB00632,
DB00433,
DB01194,
DB00273,
DB02530,

Solution

  • The unexpected error you are seeing with output like "D,B,0,0,6,3,2" is due to writer.writerow() expecting a list or iterable argument. The string DB00632 is then iterated into characters and CSV output has each letter separated by a comma without using a CSV writer.

    If just want to append a comma (,) to end of each drug id then can just output the drug name followed by a comma and a new line.

    Note the CSV file doesn't yet have a header line and there is nothing in the second column.

    with open('drug_list.txt') as f:
        with open('integrated_x.csv', 'w') as out_file:
            for line in f:
                line = line.strip()
                print(line)
                out_file.write(f"{line},\n")
    

    If input looks like a drug id on each line (e.g. DB00632) then the output would be as expected:

    DB00632,
    DB00433,
    DB01194,
    DB00273,
    DB02530,