我有一个包含数据的File1.csv(每个数据都在新行,新行)
7F
1
4
FF
73
9F
7F
1
4
FF
73
9F
7F
1
4
FF
73
9F
我想将其转换为下面显示的格式并将其另存为File2.csv
7F,1,4,FF,73,9F
7F,1,4,FF,73,9F
import csv #import the CSV module in python
f = open('File1.csv', "rb")
csv_f = [i for i in csv.reader(f)]
f.close()
tempVal1=csv_f[1]+csv_f[2]+csv_f[3]+csv_f[4]+csv_f[5]+csv_f[6]
tempVal2=csv_f[7]+csv_f[8]+csv_f[9]+csv_f[10]+csv_f[11]+csv_f[12]
with open('File2.csv', "wb") as csv_file: #open the file to write, use "wb" for write access
writer = csv.writer(csv_file, delimiter=',')
writer.writerow(tempVal1) #write data into the file
writer.writerow(tempVal2) #write data into the file
我想以高效的方式编写上面的程序(用于,while循环),这样我就不使用tempVal1,2变量了,我想在我的代码中使用逻辑,我可以读取'7F'值并写入数据从逗号分隔的新行7F开始,任何人都可以帮助我吗? 我担心的是 - 1.如何读取行'7F'中的值? 2.如何添加for或while循环逻辑而不是添加并将其存储在tempVal变量中?
答案 0 :(得分:0)
假设您在9f
值之后创建了一个新行:
import csv
with open("C:/path/a.txt","r") as f,open("C:/path/a.csv" ,"wb") as w:
temp = []
writer = csv.writer(w)
for line in f:
temp.append(line.strip())
if "9F" in line:
writer.writerow(temp)
temp = []