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

writing of data from txt-file to .csv file python

I have some lines of test data in a txt-file saved like this:

$PZFM1,A,1,0,0,0,0,0,2,3,008,000,000,201149*6A
$PZFM2,A,1,000,000,000,011*43
$PZFM3,A,1,800*56
$PZFM4,A,1,0000*69

I would like to read it in line by line and write into a csv-file using python. My code so far:

import csv

testdata_name = 'data_test.txt'                                                                         

save_data = open('data.csv','w',newline='', encoding='utf-8')
writer = csv.writer(save_data)

test = open(testdata_name,'r')
 
while 1:     
    line_test = test.readline()
    print("Input: " + line_test)
    writer.writerow(line_test)

with the output 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

$,P,Z,F,M,1,",",A,",",1,",",0,",",0,",",0,",",0,",",0,",",2,",",3,",",0,0,8,",",0,0,0,",",0,0,0,",",2,0,1,1,4,9,*,6,A,"
"
$,P,Z,F,M,2,",",A,",",1,",",0,0,0,",",0,0,0,",",0,0,0,",",0,1,1,*,4,3,"
"
$,P,Z,F,M,3,",",A,",",1,",",8,0,0,*,5,6,"
"
$,P,Z,F,M,4,",",A,",",1,",",0,0,0,0,*,6,9

However, the data in the csv file does not look one-to-one like that from the txt file and that is actually my goal. What am I doing wrong?

>Solution :

writer.writerow(line_test) expects a List containing the content of the columns of the row you want to write. However, you feed the writerow function with a string (str).

Since a string is an array of character, it creates a column for each character in your line.

To separate your fields (if your fields are separated by a comma), you can use

writer.writerow(line_test.split(","))

This way, the string is first transformed in an array containing with each field.

However, as @Fang said, your file is already a CSV, you might be able to open it with a spreadsheet software after changing the extension

Edit: The quotation marks around the commas are placed in order to differentiate the comma as a delimiter and the comma as a character

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