python練習專案九 從CSV 檔案中刪除表頭

2021-10-02 00:04:26 字數 2286 閱讀 7085

假設你有乙個枯燥的任務,要刪除幾百csv 檔案的第一行。也許你會將它們送入乙個自動化的過程,只需要資料,不需要每列頂部的表頭。可以在excel 中開啟每個檔案,刪除第一行,並重新儲存該檔案,但這需要幾個小時。讓我們寫乙個程式來做這件事。該程式需要開啟當前工作目錄中所有擴充套件名為.csv 的檔案,讀取csv 檔案的內容,並除掉第一行的內容重新寫入同名的檔案。這將用新的、無表頭的內容替換csv 檔案的舊內容。

注:與往常一樣,當你寫程式修改檔案時,一定要先備份這些檔案,以防萬一你的程式沒有按期望的方式工作。你不希望意外地刪除原始檔案。

csv.reader()reader 物件

用csv 模組從csv 檔案中讀取資料,需要建立乙個reader 物件。reader 物件讓你迭代遍歷csv 檔案中的每一行。

首先用open()函式開啟它,就像開啟任何其他文字檔案一樣。但是,不用在open()返回的file 物件上呼叫read()或readlines()方法,而是將它傳遞給csv.reader()函式。這將返回乙個reader 物件,供使用。

在for 迴圈中,從reader 物件讀取資料

總的來說,該程式必須做到以下幾點:

在**層面上,這意味著該程式需要做到以下幾點:

①迴圈遍歷從os.listdir()得到的檔案列表,跳過非csv 檔案。

②建立乙個csv reader 物件,讀取該檔案的內容,利用line_num 屬性確定要跳過哪一行。

③建立乙個csv writer 物件,將讀入的資料寫入新檔案。

#! python3

# removecsvheader.py - removes the header from all csv files in the current

# working directory.

import csv, os

os.makedirs

('headerremoved'

, exist_ok=true)

# loop through every file in the current working directory.

for csvfilename in os.

listdir

('.'):

if not csvfilename.

endswith

('.csv'):

continue # skip non-csv files

print

('removing header from '

+ csvfilename +

'...'

) # read the csv file in

(skipping first row)

. csvrows =

csvfileobj =

open

(csvfilename)

readerobj = csv.

reader

(csvfileobj)

for row in readerobj:

if readerobj.line_num ==1:

continue # skip first row

csvrows.

(row)

csvfileobj.

close()

# write out the csv file.

csvfileobj =

open

(os.path.

join

('headerremoved'

, csvfilename)

,'w'

, newline='')

csvwriter = csv.

writer

(csvfileobj)

for row in csvrows:

csvwriter.

writerow

(row)

csvfileobj.

close

()

Python之csv檔案從MySQL資料庫匯入匯出

csv檔案匯入mysql資料庫import pymysql import csv import codecs defget conn conn pymysql.connect host localhost port 3306,user root passwd root db test csv cha...

Python練習 CSV檔案的讀取與修改

csv comma separated values 逗號分隔值格式,是一種常見的資料格式,以純文字形式儲存 資料。本練習初衷是為了處理實驗中常用的資料,該資料預設格式為.csv,其中包含冗長的檔案頭和其他一些引數,在匯出作圖的過程中不得不重複性地開啟 選中 關閉資料。這裡將先以最簡單的處理方式修改...

Python程式設計 從入門到實踐第九章練習9 4

先對各類被匯入檔案進行類的分配 class restaurant def init self,restaurant name,cuisine type 初始化屬性 self.restaurant name restaurant name self.cuisine type cuisine type ...