在資料處理過程中,經常需要移除 CSV 檔案的標題列。以下 Python 指令碼利用 csv 模組和 os 模組,實作了批次移除 CSV 檔案標題列的功能。指令碼會先建立一個名為 headerRemoved 的資料夾,用於存放處理後的檔案。接著,它會遍歷目前目錄下的所有 .csv 檔案,逐一讀取檔案內容,跳過第一行(標題列),然後將剩餘的資料寫入新的 CSV 檔案中。新的檔案會儲存在 headerRemoved 資料夾下,檔名與原始檔案相同。這個方法可以有效率地處理大量 CSV 檔案,避免手動操作的繁瑣。
11. 如何向儲存在變數 doc 中的 Document 物件新增一個包含文字 ‘Hello, there!’ 的段落?
您可以使用 doc.add_paragraph('Hello, there!') 方法來新增一個新段落。
12. Word 檔案中可用的標題級別由哪些整數表示?
Word 檔案中可用的標題級別由整數 0 到 4 表示。
練習程式
PDF Paranoia
以下是使用 os.walk() 函式遍歷資料夾和子資料夾,並使用提供的密碼加密 PDF 檔案的指令碼:
import os
import PyPDF2
def encrypt_pdf(file_path, password):
pdf_file = open(file_path, 'rb')
pdf_reader = PyPDF2.PdfFileReader(pdf_file)
pdf_writer = PyPDF2.PdfFileWriter()
for page_num in range(pdf_reader.numPages):
pdf_writer.addPage(pdf_reader.getPage(page_num))
pdf_writer.encrypt(password)
encrypted_file_path = file_path + '_encrypted.pdf'
encrypted_pdf_file = open(encrypted_file_path, 'wb')
pdf_writer.write(encrypted_pdf_file)
pdf_file.close()
encrypted_pdf_file.close()
def main():
password = input('Enter password: ')
for root, dirs, files in os.walk('.'):
for file in files:
if file.endswith('.pdf'):
file_path = os.path.join(root, file)
encrypt_pdf(file_path, password)
if __name__ == '__main__':
main()
以下是使用提供的密碼解密 PDF 檔案的指令碼:
import os
import PyPDF2
def decrypt_pdf(file_path, password):
pdf_file = open(file_path, 'rb')
pdf_reader = PyPDF2.PdfFileReader(pdf_file)
if pdf_reader.isEncrypted:
try:
pdf_reader.decrypt(password)
except PyPDF2.exceptions.PdfReadError:
print('Incorrect password')
return
decrypted_file_path = file_path + '_decrypted.pdf'
decrypted_pdf_file = open(decrypted_file_path, 'wb')
pdf_writer = PyPDF2.PdfFileWriter()
for page_num in range(pdf_reader.numPages):
pdf_writer.addPage(pdf_reader.getPage(page_num))
pdf_writer.write(decrypted_pdf_file)
pdf_file.close()
decrypted_pdf_file.close()
def main():
password = input('Enter password: ')
for root, dirs, files in os.walk('.'):
for file in files:
if file.endswith('_encrypted.pdf'):
file_path = os.path.join(root, file)
decrypt_pdf(file_path, password)
if __name__ == '__main__':
main()
Custom Invitations
以下是生成 Word 檔案的指令碼:
import docx
def create_invitation(doc, name):
paragraph = doc.add_paragraph()
run = paragraph.add_run()
run.text = f'Dear {name},'
run.font.size = docx.shared.Pt(12)
run.font.name = 'Calibri'
paragraph = doc.add_paragraph()
run = paragraph.add_run()
run.text = 'You are cordially invited to our party!'
run.font.size = docx.shared.Pt(12)
run.font.name = 'Calibri'
paragraph = doc.add_paragraph()
run = paragraph.add_run()
run.text = 'Please RSVP by March 1st.'
run.font.size = docx.shared.Pt(12)
run.font.name = 'Calibri'
def main():
doc = docx.Document()
with open('guests.txt', 'r') as f:
for line in f:
name = line.strip()
create_invitation(doc, name)
doc.add_page_break()
doc.save('invitations.docx')
if __name__ == '__main__':
main()
PDF Password Breaker
以下是嘗試使用字典中單詞破解 PDF 密碼的指令碼:
import PyPDF2
def crack_password(file_path, dictionary_file):
with open(dictionary_file, 'r') as f:
words = [line.strip() for line in f]
pdf_file = open(file_path, 'rb')
pdf_reader = PyPDF2.PdfFileReader(pdf_file)
for word in words:
try:
pdf_reader.decrypt(word)
print(f'Password found: {word}')
return
except PyPDF2.exceptions.PdfReadError:
pass
try:
pdf_reader.decrypt(word.upper())
print(f'Password found: {word.upper()}')
return
except PyPDF2.exceptions.PdfReadError:
pass
def main():
file_path = input('Enter PDF file path: ')
dictionary_file = 'dictionary.txt'
crack_password(file_path, dictionary_file)
if __name__ == '__main__':
main()
CSV, JSON 和 XML 檔案
CSV、JSON 和 XML 是用於序列化資料的檔案格式。序列化將資料轉換為字串,以便儲存程式的工作到文字檔案、透過網際網路連線傳輸或甚至複製和貼上到電子郵件中。Python 有 csv、json 和 xml 模組來幫助您使用這些檔案格式。
CSV檔案格式及Python讀寫方法
CSV(Comma Separated Values)是一種簡單的試算表格式,適合儲存具有相同欄位的多行資料。每行代表試算表的一行,逗號分隔同一行的不同欄位。例如,以下是一個CSV檔案的內容:
4/5/2035 13:34,Apples,73
4/5/2035 3:41,Cherries,85
4/6/2035 12:46,Pears,14
4/8/2035 8:59,Oranges,52
4/10/2035 2:07,Apples,152
4/10/2035 18:10,Bananas,23
4/10/2035 2:40,Strawberries,98
這個CSV檔案可以被視為一個列表的列表,其中每個內部列表代表一行資料。
讀取CSV檔案
要讀取CSV檔案,可以使用Python的csv模組。首先,需要開啟CSV檔案並建立一個csv.reader物件。然後,可以使用list()函式將csv.reader物件轉換為一個列表的列表。以下是示例程式碼:
import csv
example_file = open('example3.csv')
example_reader = csv.reader(example_file)
example_data = list(example_reader)
print(example_data)
輸出結果:
[['4/5/2035 13:34', 'Apples', '73'],
['4/5/2035 3:41', 'Cherries', '85'],
['4/6/2035 12:46', 'Pears', '14'],
['4/8/2035 8:59', 'Oranges', '52'],
['4/10/2035 2:07', 'Apples', '152'],
['4/10/2035 18:10', 'Bananas', '23'],
['4/10/2035 2:40', 'Strawberries', '98']]
可以使用example_data[row][col]的語法來存取特定行和欄位的資料。例如:
print(example_data[0][0]) # 輸出:'4/5/2035 13:34'
print(example_data[0][1]) # 輸出:'Apples'
print(example_data[0][2]) # 輸出:'73'
CSV檔案的優點和限制
CSV檔案的優點在於其簡單性和通用性。許多應用程式和程式語言都支援CSV檔案,可以在文字編輯器中檢視和編輯。然而,CSV檔案也有以下限制:
- 沒有多個資料型別,每個值都是字串
- 沒有字型大小或顏色設定
- 沒有多個工作表
- 不能指定單元格寬度或高度
- 不能合併單元格
- 不能嵌入影像或圖表
使用csv模組的原因
雖然可以使用open()函式和read()或readlines()方法來讀取CSV檔案,但使用csv模組可以提供更可靠的方式來讀寫CSV檔案。因為CSV檔案有特殊的跳脫字元,可以包含逗號和其他字元作為值的一部分,而split()方法不能正確處理這些跳脫字元。因此,使用csv模組可以避免這些潛在的陷阱。
存取 CSV 檔案中的資料
在 Python 中,csv 模組提供了一個方便的方式來讀取和寫入 CSV 檔案。下面是如何存取 CSV 檔案中的資料的範例。
使用 csv.reader 來存取資料
當您有一個 CSV 檔案時,您可以使用 csv.reader 來讀取檔案中的資料。以下是範例程式碼:
import csv
# 開啟 CSV 檔案
example_file = open('example3.csv', 'r')
# 建立 csv.reader 物件
example_reader = csv.reader(example_file)
# 使用 for 迴圈來存取資料
for row in example_reader:
print('Row #' + str(example_reader.line_num) + str(row))
這個程式碼會開啟名為 example3.csv 的檔案,並使用 csv.reader 來讀取檔案中的資料。然後,它會使用 for 迴圈來存取每一行的資料,並印出行號和資料。
存取特定欄位的資料
如果您想要存取特定欄位的資料,您可以使用索引來存取。例如,以下程式碼會存取第二行第二欄的資料:
example_data = list(example_reader)
print(example_data[1][1]) # 第二行第二欄
這個程式碼會將 example_reader 物件轉換成列表,並存取第二行第二欄的資料。
使用 csv.reader 來處理大型 CSV 檔案
當您有一個大型 CSV 檔案時,使用 csv.reader 來讀取檔案中的資料可以幫助您節省記憶體。以下是範例程式碼:
import csv
# 開啟 CSV 檔案
example_file = open('example3.csv', 'r')
# 建立 csv.reader 物件
example_reader = csv.reader(example_file)
# 使用 for 迴圈來存取資料
for row in example_reader:
print('Row #' + str(example_reader.line_num) + str(row))
這個程式碼會開啟名為 example3.csv 的檔案,並使用 csv.reader 來讀取檔案中的資料。然後,它會使用 for 迴圈來存取每一行的資料,並印出行號和資料。
圖表翻譯:
這個圖表顯示了使用 csv.reader 來存取 CSV 檔案中的資料的流程。
CSV檔案讀寫
CSV(Comma Separated Values)是一種廣泛使用的檔案格式,適用於儲存和交換表格資料。在Python中,csv模組提供了方便的功能來讀寫CSV檔案。
讀取CSV檔案
要讀取CSV檔案,首先需要匯入csv模組並建立一個reader物件。然後,您可以迴圈遍歷reader物件中的行,每行是一個值的列表。以下是範例程式碼:
import csv
with open('example.csv', 'r') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print(row)
在這個範例中,open函式用於開啟CSV檔案,csv.reader函式用於建立reader物件。然後,迴圈遍歷reader物件中的行,並將每行的值列印出來。
寫入CSV檔案
要寫入CSV檔案,需要建立一個writer物件。以下是範例程式碼:
import csv
with open('output.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['spam', 'eggs', 'bacon'])
writer.writerow(['Hello, world!', 'eggs', 'bacon'])
writer.writerow([1, 2, 3.141592, 4])
在這個範例中,open函式用於開啟CSV檔案,csv.writer函式用於建立writer物件。然後,使用writerow方法將值寫入CSV檔案中。
使用Tab分隔符
如果您想要使用Tab分隔符而不是逗號,您可以使用csv模組的delimiter引數。以下是範例程式碼:
import csv
with open('output.tsv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile, delimiter='\t')
writer.writerow(['spam', 'eggs', 'bacon'])
在這個範例中,delimiter引數被設定為\t,表示使用Tab分隔符。
內容解密:
csv模組提供了方便的功能來讀寫CSV檔案。csv.reader函式用於建立reader物件。csv.writer函式用於建立writer物件。writerow方法用於將值寫入CSV檔案中。delimiter引數用於設定分隔符。
圖表翻譯:
這個流程圖展示了讀取和寫入CSV檔案的過程。
CSV檔案的讀寫
CSV(Comma Separated Values)是一種常見的檔案格式,廣泛用於資料交換和儲存。Python的csv模組提供了方便的方式來讀寫CSV檔案。
基本讀寫
要讀寫CSV檔案,首先需要開啟檔案並建立一個reader或writer物件。以下是基本的讀寫範例:
import csv
# 開啟檔案
with open('example.csv', 'r') as csvfile:
# 建立reader物件
reader = csv.reader(csvfile)
# 讀取檔案內容
for row in reader:
print(row)
# 開啟檔案
with open('output.csv', 'w', newline='') as csvfile:
# 建立writer物件
writer = csv.writer(csvfile)
# 寫入檔案內容
writer.writerow(['Hello, world!', 'egg'])
writer.writerow([1, 2, 3.141592, 4])
自訂分隔符和行終止符
可以使用delimiter和lineterminator引數自訂分隔符和行終止符。例如:
with open('output.tsv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile, delimiter='\t', lineterminator='\n\n')
writer.writerow(['spam', 'eggs', 'bacon', 'ham'])
writer.writerow(['Hello, world!', 'egg', 'bacon', 'ham'])
writer.writerow([1, 2, 3.141592, 4])
處理標頭列
如果CSV檔案包含標頭列,可以使用DictReader和DictWriter物件來讀寫檔案。這些物件使用字典來表示每一列,標題列的值作為字典的鍵。
import csv
# 開啟檔案
with open('exampleWithHeader3.csv', 'r') as csvfile:
# 建立DictReader物件
dict_reader = csv.DictReader(csvfile)
# 讀取檔案內容
for row in dict_reader:
print(row['Timestamp'], row['Fruit'], row['Quantity'])
寫入檔案
可以使用DictWriter物件來寫入CSV檔案。以下是範例:
import csv
# 開啟檔案
with open('outputWithHeader.csv', 'w', newline='') as csvfile:
# 建立DictWriter物件
fieldnames = ['Timestamp', 'Fruit', 'Quantity']
dict_writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
# 寫入標題列
dict_writer.writeheader()
# 寫入檔案內容
dict_writer.writerow({'Timestamp': '2023-03-01', 'Fruit': 'Apples', 'Quantity': 10})
dict_writer.writerow({'Timestamp': '2023-03-02', 'Fruit': 'Bananas', 'Quantity': 20})
以上是Python中讀寫CSV檔案的基本方法。可以根據需要自訂分隔符、行終止符和標題列等引數。
CSV檔案處理:讀寫與修改
CSV(Comma Separated Values)是一種純文字檔案格式,常用於儲存和交換表格資料。Python的csv模組提供了方便的方式來讀寫CSV檔案。
讀取CSV檔案
要讀取CSV檔案,可以使用csv.reader物件。這個物件會將每一行CSV檔案轉換成一個列表,其中每個元素代表一欄的值。
import csv
with open('example.csv', 'r') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print(row)
如果CSV檔案有標題行,可以使用csv.DictReader物件來讀取檔案。這個物件會將每一行轉換成一個字典,其中每個鍵值對應到一欄的名稱和值。
import csv
with open('example.csv', 'r') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
print(row)
寫入CSV檔案
要寫入CSV檔案,可以使用csv.writer物件。這個物件提供了writerow方法來寫入一行資料。
import csv
with open('output.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['Name', 'Age', 'City'])
writer.writerow(['John', 25, 'New York'])
writer.writerow(['Alice', 30, 'Los Angeles'])
如果需要寫入字典資料,可以使用csv.DictWriter物件。這個物件提供了writeheader方法來寫入標題行,和writerow方法來寫入一行資料。
import csv
with open('output.csv', 'w', newline='') as csvfile:
fieldnames = ['Name', 'Age', 'City']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'Name': 'John', 'Age': 25, 'City': 'New York'})
writer.writerow({'Name': 'Alice', 'Age': 30, 'City': 'Los Angeles'})
修改CSV檔案
要修改CSV檔案,可以先讀取檔案,然後修改資料,最後寫入新的檔案。
import csv
# 讀取檔案
with open('input.csv', 'r') as csvfile:
reader = csv.reader(csvfile)
data = list(reader)
# 修改資料
data[0][0] = '新標題'
# 寫入新的檔案
with open('output.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerows(data)
專案:移除CSV檔案的標題行
要移除CSV檔案的標題行,可以使用以下程式碼:
import csv
import os
# 取得當前工作目錄下的所有CSV檔案
for filename in os.listdir():
if filename.endswith('.csv'):
# 讀取檔案
with open(filename, 'r') as csvfile:
reader = csv.reader(csvfile)
data = list(reader)[1:] # 移除第一行
# 寫入新的檔案
with open(filename, 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerows(data)
這個程式碼會移除當前工作目錄下的所有CSV檔案的標題行。請注意,這個程式碼會覆寫原始檔案,所以請先備份您的檔案。
移除 CSV 檔案的標題列
步驟 1:建立目錄和迴圈檔案
首先,我們需要建立一個目錄來儲存移除標題列的 CSV 檔案。使用 os.makedirs() 函式可以建立目錄,如果目錄已經存在,則不會發生錯誤。接下來,我們迴圈遍歷當前工作目錄下的所有檔案,檢查每個檔案是否為 CSV 檔案。如果不是,則跳過此檔案。
import csv, os
os.makedirs('headerRemoved', exist_ok=True)
for csv_filename in os.listdir('.'):
if not csv_filename.endswith('.csv'):
continue # 跳過非 CSV 檔案
print('移除 ' + csv_filename + ' 的標題列')
步驟 2:讀取 CSV 檔案
現在,我們需要讀取 CSV 檔案並跳過第一行(標題列)。為了實作這一點,我們使用 csv.reader 物件來讀取檔案,並使用 line_num 屬性來檢查當前行號。如果是第一行,則跳過它。
csv_rows = []
csv_file_obj = open(csv_filename)
reader_obj = csv.reader(csv_file_obj)
for row in reader_obj:
if reader_obj.line_num == 1:
continue # 跳過第一行
csv_rows.append(row)
csv_file_obj.close()
步驟 3:寫入新 CSV 檔案
最後,我們需要將 csv_rows 列表寫入一個新 CSV 檔案中。這個新檔案將儲存在 headerRemoved 目錄中。使用 csv.writer 物件可以實作這一點。
new_csv_filename = os.path.join('headerRemoved', csv_filename)
new_csv_file_obj = open(new_csv_filename, 'w', newline='')
writer_obj = csv.writer(new_csv_file_obj)
for row in csv_rows:
writer_obj.writerow(row)
new_csv_file_obj.close()
完整程式碼
以下是完整的程式碼:
import csv, os
os.makedirs('headerRemoved', exist_ok=True)
for csv_filename in os.listdir('.'):
if not csv_filename.endswith('.csv'):
continue # 跳過非 CSV 檔案
print('移除 ' + csv_filename + ' 的標題列')
csv_rows = []
csv_file_obj = open(csv_filename)
reader_obj = csv.reader(csv_file_obj)
for row in reader_obj:
if reader_obj.line_num == 1:
continue # 跳過第一行
csv_rows.append(row)
csv_file_obj.close()
new_csv_filename = os.path.join('headerRemoved', csv_filename)
new_csv_file_obj = open(new_csv_filename, 'w', newline='')
writer_obj = csv.writer(new_csv_file_obj)
for row in csv_rows:
writer_obj.writerow(row)
new_csv_file_obj.close()
內容解密:
上述程式碼的主要目的是移除 CSV 檔案的標題列。首先,建立一個目錄來儲存移除標題列的 CSV 檔案。接下來,迴圈遍歷當前工作目錄下的所有檔案,檢查每個檔案是否為 CSV 檔案。如果不是,則跳過此檔案。然後,讀取 CSV 檔案並跳過第一行(標題列)。最後,將剩餘的行寫入一個新 CSV 檔案中。這個新檔案將儲存在 headerRemoved 目錄中。
圖表翻譯:
@startuml
skinparam backgroundColor #FEFEFE
skinparam componentStyle rectangle
title Python批次移除CSV檔案標題列
package "Python 應用架構" {
package "應用層" {
component [主程式] as main
component [模組/套件] as modules
component [設定檔] as config
}
package "框架層" {
component [Web 框架] as web
component [ORM] as orm
component [非同步處理] as async
}
package "資料層" {
database [資料庫] as db
component [快取] as cache
component [檔案系統] as fs
}
}
main --> modules : 匯入模組
main --> config : 載入設定
modules --> web : HTTP 處理
web --> orm : 資料操作
orm --> db : 持久化
web --> cache : 快取查詢
web --> async : 背景任務
async --> fs : 檔案處理
note right of web
Flask / FastAPI / Django
end note
@enduml上述流程圖描述了程式碼的執行流程。首先,建立目錄,然後迴圈檔案,檢查每個檔案是否為 CSV。如果是,則讀取檔案並跳過第一行,最後寫入新 CSV 檔案。
CSV檔案處理:移除標題列
簡介
CSV(Comma Separated Values)檔案是一種常見的資料儲存格式,廣泛用於資料交換和儲存。然而,在某些情況下,移除CSV檔案的標題列是必要的。這篇文章將介紹如何使用Python程式語言來移除CSV檔案的標題列。
程式碼
import csv
import os
# 迴圈處理每個CSV檔案
for csv_filename in os.listdir('.'):
if not csv_filename.endswith('.csv'):
continue # 跳過非CSV檔案
# 讀取CSV檔案
with open(csv_filename, 'r', newline='') as csv_file_obj:
csv_reader = csv.reader(csv_file_obj)
csv_rows = list(csv_reader)[1:] # 移除標題列
# 寫入新的CSV檔案
with open(os.path.join('headerRemoved', csv_filename), 'w', newline='') as csv_file_obj:
csv_writer = csv.writer(csv_file_obj)
for row in csv_rows:
csv_writer.writerow(row)
print(f'Removing header from {csv_filename}...')
執行結果
當程式執行完成後,會在console中印出每個CSV檔案的名稱,表示已經移除標題列。
相似程式的想法
以下是一些與CSV檔案處理相關的程式想法:
- 比較不同行或檔案的資料:可以撰寫程式來比較不同行或多個CSV檔案中的資料。
- 複製特定資料到Excel檔案:可以撰寫程式來複製特定資料從CSV檔案到Excel檔案,或反之亦然。
- 檢查無效資料或格式錯誤:可以撰寫程式來檢查CSV檔案中的無效資料或格式錯誤,並提醒使用者。
- 讀取CSV檔案作為輸入:可以撰寫程式來讀取CSV檔案作為輸入,然後進行進一步的處理。
從檔案格式處理的實務角度來看,Python 的 csv 模組提供簡潔有效的機制來讀寫 CSV 檔案。藉由 csv.reader 和 csv.writer,開發者可以輕鬆處理結構化資料,包含讀取、寫入、修改,甚至移除標題列等操作。然而,csv 模組本身的功能有限,例如缺乏資料型態推斷、無法處理複雜的資料結構。展望未來,整合更進階的資料處理函式庫,例如 pandas,將能提升 CSV 檔案處理的效率和彈性,尤其在處理大型資料集、資料清洗、轉換和分析方面更具優勢。對於追求高效能和資料分析能力的開發者而言,pandas 等工具將是不可或缺的利器。玄貓認為,熟練掌握 csv 模組的基礎用法,並結合更強大的資料處理工具,將賦予開發者處理各式資料格式的堅實能力。