Edwin Reyes
Edwin Reyes

Reputation: 97

Write column data from csv in to a line / row in a text file

im working in a script to read a .csv file , read an specific column and write it in a txt file, the problem is, that the extracted data is written in a column, in this form:

primary_channel
2
1
0
0
2
0
1
2
1

and i need it in a line,like this:

2,1,0,0,2,0,1,2,1

my code is the next,

import sys
import csv
import copy
import os
import random
import fileinput
import sys, glob
from io import StringIO
from collections import OrderedDict
import sys
#scriptname,f1name,f2name=sys.argv

fieldnames=['node_code;node_type;wlan_code;destination_id;x(m);y(m);z(m);primary_channel;min_channel_allowed;max_channel_allowed;cw;cw_stage;tpc_min(dBm);tpc_default(dBm);tpc_max(dBm);cca_min(dBm);cca_default(dBm);cca_max(dBm);tx_antenna_gain;rx_antenna_gain;channel_bonding_model;modulation_default;central_freq (GHz);lambda;ieee_protocol;traffic_load(pkts/s)']

main={}
with open('nodos_cambiados_1.csv','r') as infile,open('lista.txt','w') as outfile:
     reader = csv.DictReader(infile,delimiter=";" )
     writer = csv.DictWriter(outfile,fieldnames=['primary_channel'],delimiter=",",extrasaction='ignore')
     writer.writeheader()
     for row in reader:
         next(reader) 
         for values in row:
             if row['node_type']=='0' in row:
                main.update({row['primary_channel']:()})

         writer.writerow(row)

I will be very grateful for the help you can give me

Upvotes: 0

Views: 465

Answers (2)

Johan Schiff
Johan Schiff

Reputation: 691

Using DictWriter seems like overcomplicating things, if you just want to write numbers on a row. I think something like this will suffice:

with open('nodos_cambiados_1.csv','r') as infile,open('lista.txt','w') as outfile:
     reader = csv.DictReader(infile,delimiter=';')
     outfile.write(','.join(row.get('primary_channel') for row in reader))

Upvotes: 1

Ami Tavory
Ami Tavory

Reputation: 76297

In the call to DictWriter, try adding newline=''. As the documentation notes:

Any other optional or keyword arguments are passed to the underlying writer instance.

Upvotes: 1

Related Questions