簡體   English   中英

如何使用python 2.7.9修改csv文件中的多個列和行

[英]How to modify multiple columns and rows in a csv file using python 2.7.9

我有一個包含數據的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變量中?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM