pythonでファイル読み書きをしてCSVを作成してみる

2020年12月21日


with open('sample.txt', 'r') as file:
    document = file.read()
    print(document)

#結果:sample.txtに記載されている文字が出力される
hello

with open('sample.txt', 'w') as file:
    document = file.write('world')

#結果:sample.txtに記載されている文字が上書きされる
world

import csv

with open('sample.csv', 'w') as file:
    #書き込むファイルを指定
    writer = csv.writer(file)
    #書き込み
    writer.writerow(['a','b','c'])
    writer.writerow(['d','e','f'])

#結果:配列の要素ががカンマ区切りで書き込まれる
a,b,c
d,e,f

ここで前回の記事を参考にスクレイピングしたテーブルをCSVファイルにしてみます。


import csv
import requests
from bs4 import BeautifulSoup

#サイトにリクエストを送りレスポンスを受ける
request = requests.get('http://houdoukyokucho.com/2020/03/24/post-533/')

#レスポンスからHTMLをオブジェクトとして取得する
soup = BeautifulSoup(request.text, 'html.parser')

#テーブルを指定
first_table = soup.find_all('table')[0]
rows        = first_table.find_all('tr') 

#書き込みファイル指定
with open('sample.csv', 'w') as file:
    writer = csv.writer(file)
    #書き込み開始
    for row in rows:
        csv_row = []
        cells = row.find_all('td')
        for cell in cells:
            csv_row.append(cell.get_text())
        writer.writerow(csv_row)

#結果
言語,コーダー呼称
Python,パイソニスタ
PHP,ペチパー
Java,SIer

自動化って本当に楽しいですね!

追記:文字化け対策の為下記の通り変更いたしました。
参考:RequestsとBeautiful Soupでのスクレイピング時に文字化けを減らす


# soup = BeautifulSoup(request.text, 'html.parser')
soup = BeautifulSoup(request.content, 'html.parser')
YouTube

2020年12月21日