Edwin Reyes
Edwin Reyes

Reputation: 97

write columns of data in a txt file in a row/line

i need help with a python code, my issue is that i write a .txt file with a column extracted from a .csv file

the data inside the txt file is like this:

2
1
0
0
2
0
1
2
1

but i need it in a row/line , and add a comma to separate the values to get finally a result in this shape

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

my code is the next:

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)']

od = OrderedDict()   
main={}
with open("nodos_cambiados_1.csv",'r') as infile, open("lista_extraida.txt",'w') as outfile:
     reader = csv.DictReader(infile,delimiter=";" )
     writer = csv.DictWriter(outfile,fieldnames=['primary_channel'],delimiter=",",extrasaction='ignore')
     writer.writeheader()
     #next(reader)
     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)

Upvotes: 1

Views: 410

Answers (1)

Mayank Porwal
Mayank Porwal

Reputation: 34046

Considering that you have the data in you txt file written in every new line, you can try this:

In [1038]: with open(filename, 'r') as f: 
      ...:     lines = f.readlines() 
      ...:                            

In [1039]: lines                                                                                                                                                                                            
Out[1039]: ['2\n', '1\n', '0\n', '0\n', '2\n', '0\n', '1\n', '2\n', '1\n']

In [1040]: lines = [item.strip() for item in lines] 

In [1038]: with open(filename_to_write, 'w') as f: 
      ...:     f.write(','.join(lines))
      ...:                            

Your new file will have all the data in one-line separated by a comma(,).

OR by the syntax that you were trying:

with open(infile, mode='r') as in_file, \
     open(outfile, mode='w') as out_file:

    lines = infile.readlines() 
    lines = [item.strip() for item in lines] 
    out_file.write(','.join(lines))

Upvotes: 1

Related Questions