How to convert CSV file which having comma delimiter to csv with only space delimiter

Viewed 59

I am trying to convert the the comma-separated csv file to space separate columns. Please see the columns of input and output file to understand the motive.

fILENAME ,sent_no ,   word ,POS ,lab,Slab
File_1 ,  sentence:1,  abc, NNP, B,NO   
                     fhj, PSP, O,O    
                     bmm ,NNP,B,NO   
                     vbn ,PSP, O,O    
                     vbn ,NN , B,NO   
                     vbn ,NNPC,B,NO  
                     . , Sym ,O,O  

I have written code

import csv
filename1 = sys.argv[1]
filename2 = sys.argv[2] 

with open(filename1) as infile, open(filename2, 'w') as outfile:
    print(infile.read())
    outfile.write(infile.read().replace(",", " "))

after this statement print(infile.read()) values are

",",F,i,l,e,n,a,m,e,",",S,e,n,t,e,n,c,e,_,n,u,m,",",W,o,r,d,",",P,O,S,",",M,E,N,T,_,L,a,b,e,l,",",S,I,N,G,L,E,_,M,E,N,T,I,O,N
0,",",f,i,l,e,_,1,",",s,e,n,t,e,n,c,e,:,1,",",a,िb,c,",",N,N,P",",B,",",N,O
1 Answers

You can read and write using pandas and the sep argument to specify the required separator:

input_df = pd.read_csv(filename1, sep=",")
input_df.to_csv(filename2, sep=" ", index=False)
Related