编写CSV Python [英] Write CSV Python
问题描述
我想从另一个csv文件(infile
)写入csv(outfile
)文件.在infile
csv数据中,这样写OF0A0C,00,D0,0F11AFCB
,我想写与infile
相同的outfile
,但是我得到这样的"\r \n 0,F,0,A,0,C,","0,0,","D,0,","0,F,1,1,A,F,C,B \r \n
我的代码是这样的:
I want write csv (outfile
) file from another csv file (infile
). In infile
csv data write like this OF0A0C,00,D0,0F11AFCB
I want to write to outfile
same asinfile
but I get like this "\r \n 0,F,0,A,0,C,","0,0,","D,0,","0,F,1,1,A,F,C,B \r \n
My code like this :
with open ("from_baryon.csv", "r") as inFile:
with open (self.filename, "a") as outFile:
for line in inFile:
OutFile = csv.writer (outFile)
OutFile.writerow (line)
写完后,我想将行中的每个数据保存到这样的列表中,例如Data = [[length_of_all_data],[length_data_row_1,datarow1],[length_data_row_2,datarow1datarow2],[length_data_row_3,datarow1datarow3]]
After write I want to save every data in row to list like this Data = [[length_of_all_data],[length_data_row_1,datarow1],[length_data_row_2,datarow1datarow2],[length_data_row_3,datarow1datarow3]]
我很困惑这样保存with列表模式.谢谢
I confused to save the with list mode like that. Thankyou
推荐答案
一些问题-
-
您应该使用
csv
模块的csv.reader()
读取输入的csv文件,而不是对其行进行迭代,因为当您对其行进行迭代时,您会在迭代中将行作为字符串返回-for line in inFile:
,然后使用OutFile.writerow(line)
回写此行,因此它将每个字符写入不同的列.
You should read the input csv file using
csv
module'scsv.reader()
, instead of iterating over its lines, since when you iterate over its lines, you get the line back as a string in the iteration -for line in inFile:
, and then you are writing this line back usingOutFile.writerow(line)
, hence it writes each character into different columns.
您无需为每行创建单独的OutFile = csv.writer (outFile)
.
You do not need to create separate OutFile = csv.writer (outFile)
for every line.
示例代码-
with open ("from_baryon.csv", "r") as inFile:
with open (self.filename, "a") as outFile:
out_file = csv.writer (outFile)
in_reader = csv.reader(inFile)
for row in in_reader:
out_file.writerow(row)
对于第二个已更新的问题,您可以创建一个列表和一个计数器来跟踪完整长度.示例-
For the second issue that is updated, you can create a list and a counter to keep track of the complete length. Example -
with open ("from_baryon.csv", "r") as inFile:
with open (self.filename, "a") as outFile:
out_file = csv.writer (outFile)
in_reader = csv.reader(inFile)
data = []
lencount = 0
for row in in_reader:
out_file.writerow(row)
tlen = len(''.join(row))
data.append([tlen] + row)
lencount += tlen
data.insert(0,[lencount])
这篇关于编写CSV Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!