[英]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我需要 python 代码的帮助,我的问题是我编写了一个 .txt 文件,其中包含从 a.csv 文件中提取的列
the data inside the txt file is like this: txt文件里面的数据是这样的:
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)
Considering that you have the data in you txt file written in every new line, you can try this:考虑到您在 txt 文件中的每一行都写入了数据,您可以试试这个:
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.