1. 程式人生 > >Python資料寫入csv格式檔案

Python資料寫入csv格式檔案

(只是傳遞,基礎知識也是根基)

Python讀取資料,並存入Excel開啟的CSV格式檔案內!

這裡需要用到bs4,csv,codecs,os模組。

廢話不多說,直接寫程式碼!該重要的內容都已經註釋了,剩下不懂的可以自己查詢一下,或者QQ群內問我。QQ群在以往的部落格中!

1 #coding:utf-8 2 from bs4 import BeautifulSoup 3 import bs4 4 import os 5 import time 6 import csv 7 import codecs 8 9 #讀取XML內的檔案資料並存入CSV格式的檔案–可使用EXCEL開啟 10 def open_file(): 11 file_folder= ‘C:\Users\Administrator\Desktop\File\Filename’ ##資料夾位置 12 if os.path.isdir(file_folder): 13 for fileName in os.listdir(file_folder): 14 # print fileName 15 info(fileName) ##讀取檔名字 16 def info(fileName): 17 soup = bs4.BeautifulSoup(open(‘C:/Users/Administrator/Desktop/File/Filename/’+fileName)) 18 a = soup.find_all(‘mxxx’) 19 info = [] 20 for i in a: 21 dt=[] 22 dt.append(i.find(‘xx’).get_text().strip()) 23 dt.append( i.find(‘xx’).get_text().strip()) 24 dt.append(i.find(‘xx’).get_text().strip()) 25 dt.append(i.find(‘xx’).get_text().strip()+’\n’) 26 dt.append( i.find(‘xx’).get_text().strip()) 27 dt.append(i.find(‘xx’).get_text().strip()) 28 dt.append(float( i.find(‘xx’).get_text().strip()) + float(i.find(‘xx’).get_text().strip())) 29 info.append(dt) 30 with open(“Ex_info.csv”,”ab+”) as csvfile: ##“ ab+ ”去除空白行,又叫換行! 31 csvfile.write(codecs.BOM_UTF8) ##存入表內的文字格式 32 writer = csv.writer(csvfile) #存入表時所使用的格式 33 writer.writerow([‘表頭’,’表頭’]) 34 writer.writerows(info) #寫入表 35 36 if name

== ‘main‘: 37 open_file() 這裡主要三部分,我呼叫的測試使用的xml內的資料,這裡使用的bs4來解析xml檔案。

解釋第一部分:

開啟資料夾,並獲取到檔案的名字,因為檔案有多個,所以使用了os模組的函式來開啟檔案

1 file_folder= ‘C:\Users\Administrator\Desktop\File\Filename’ ##資料夾位置 2 if os.path.isdir(file_folder): 3 for fileName in os.listdir(file_folder): 4 # print fileName 5 info(fileName) ##讀取檔名字 fileName就是我們所獲取的檔案的名字。

第二部分:

獲取檔名字後需要使用bs4模組來開啟檔案,因為多個檔案,所以將解析過程寫入函式內。

1 def info(fileName): 2 soup = bs4.BeautifulSoup(open(‘C:/Users/Administrator/Desktop/File/Filename/’+fileName)) 3 a = soup.find_all(‘mxxx’) 4 info = [] 5 for i in a: 6 dt=[] 7 dt.append(i.find(‘xx’).get_text().strip()) 8 dt.append( i.find(‘xx’).get_text().strip()) 9 dt.append(i.find(‘xx’).get_text().strip()) 10 dt.append(i.find(‘xx’).get_text().strip()+’\n’) 11 dt.append( i.find(‘xx’).get_text().strip()) 12 dt.append(i.find(‘xx’).get_text().strip()) 13 dt.append(float( i.find(‘xx’).get_text().strip()) + float(i.find(‘xx’).get_text().strip())) 14 info.append(dt) 開啟資料夾後取出檔案,並解析後使用BeautifulSoup的解析網頁方法來獲取資料,’mxxx’與’xx’都是樹的名字。

第三部分:

將資料寫入csv檔案,這裡的資料都是List格式,並需要遍歷。

1 with open(“Ex_info.csv”,”ab+”) as csvfile: ##“ ab+ ”去除空白行,又叫換行! 2 csvfile.write(codecs.BOM_UTF8) ##存入表內的文字格式 3 writer = csv.writer(csvfile) #存入表時所使用的格式 4 writer.writerow([‘表頭’,’表頭’,’表頭’,’表頭’]) 5 writer.writerows(info) #寫入表 這裡的表頭要和我們上面獲取的資料列一致,不然會出現錯誤。寫入檔案的格式有 “ w ”,” a+ “,” ab+ “等,這裡使用的是“ ab+ ”,去除空行!

還有我們如果存入的資料是1000000000這樣的,在excel內是E+17的顯示,所有在獲取資料的時候最後面加 “\n”。最後寫入表內,並開啟!