如何使用python2.7.9修改csv文件中的多个列和行

2024-06-16 10:02:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个File1.csv包含数据(每个数据都在新行、新行上)

7F
1
4
FF
73
9F
7F
1
4
FF
73
9F
7F
1
4
FF
73
9F

我想把它转换成下面显示的格式,并保存为File2.csv

^{pr2}$
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

我想用一种有效的方式写上面的程序(for,while循环),这样我就不用tempVal1,2变量了,我想在我的代码中使用逻辑,在这里我可以读取'7F'值,并将从7F开始的数据以逗号分隔的新行写入,有人能帮我吗? 我担心的是- 1如何读取“7F”行中的值? 2如何添加for或while循环逻辑,而不是将加法放入tempVal变量中?在


Tags: csvthe数据inimportforopenfile1
1条回答
网友
1楼 · 发布于 2024-06-16 10:02:31

假设您在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 = []

相关问题 更多 >