我想从另一个csv文件(viewDidDisAppear
)中写入csv(outfile
)文件。在infile
csv数据中写这样的infile
我想写OF0A0C,00,D0,0F11AFCB
与outfile
相同,但我得到这样infile
我的代码是这样的:
"\r \n 0,F,0,A,0,C,","0,0,","D,0,","0,F,1,1,A,F,C,B \r \n
写完后我想将行中的每个数据保存到列表中,如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)
我很困惑,保存这样的列表模式。三江源
答案 0 :(得分:1)
几个问题 -
您应该使用csv
模块csv.reader()
来阅读输入csv文件,而不是遍历其行,因为当您遍历其行时,您将获得返回的行作为迭代中的字符串 - for line in inFile:
,然后您使用OutFile.writerow(line)
写回此行,因此它将每个字符写入不同的列。
您不需要为每一行创建单独的OutFile = csv.writer (outFile)
。
示例代码 -
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)
编辑:对于更新的第二个问题,您可以创建一个列表和一个计数器来跟踪完整长度。示例 -
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])