Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

If just want to append a comma (,) to end of each drug ids 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,
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading