科学の箱

科学・IT・登山の話題

Python

automated the boring – day4

投稿日:2018年2月24日 更新日:

本日からOS操作。面倒くさいことを自動化するのであればOSコマンドは避けては通れない。

pythonではすでにosパッケージが用意されているので、これを利用すればコードとしてはそれほどはややこしくない。


import os
os.getcwd()
os.chdir('C:\\temp')
os.makedirs('.\\pythonwork_01')
os.chdir('.\\pythonwork_01')
os.listdir('.\\')
['a.txt', 'b.txt']
os.path.getsize('.\\a.txt')
18
os.path.listdir('.\\a.txt')

次はファイルの中身を読みだす。

hellofile = open('.\\a.txt')
hellocontent=hellofile.read()
hellocontent
'aaaaaaaaaaaaaaaa\n'

読み込んだ次は書き込み。書き込みはfileを開くときにパラメータで’w’を指定すればよい。

hellofile = open('.\\a.txt', 'w')
hellofile.write('Hello Bacon\n')
12
hellofile.write('Hello Vegetable\n')
16
hellofile.close()
hellofile = open('.\\a.txt')
hellocontent=hellofile.read()
hellocontent
'Hello Bacon\nHello Vegetable\n'

 

ファイル操作でコピーと名前変更、削除してみる。このときはosパッケージに追加してshutilを利用する。


import shutil, os
os.chdir('c:\\temp\\pythonwork_01')
shutil.copy('.\\a.txt', '.\\a_copy.txt)
File "<stdin>", line 1
shutil.copy('.\\a.txt', '.\\a_copy.txt')
'.\\a_copy.txt'
shutil.move('.\\a_copy.txt', '.\\a_02.txt')
'.\\a_02.txt'
os.unlink('.\\a_02.txt')

 

次にzipファイルについて取り扱う。正直zipファイルをコマンドラインで取り扱うシーンはあまりない気がする。例えば巨大ファイルをメールで送るにあたり圧縮しておく、使わないファイルをzip化して保管しておく等があるくらいか。


import zipfile, os
bzip = zipfile.ZipFile('.\\b.zip')
bzip.extractall()
bzip.close()

bzip = zipfile.ZipFile('.\\b.zip','w')
bzip.write('a.txt', compress_type=zipfile.ZIP_DEFLATED)
bzip.close()

bzip = zipfile.ZipFile('.\\b.zip')
bzip = zipfile.ZipFile('.\\b.zip','w')
bzip.write('a.txt', compress_type=zipfile.ZIP_DEFLATED)
bzip.close()
bzip = zipfile.ZipFile('.\\b.zip')
bzip.namelist()
['a.txt']

 

メタ情報

inarticle



メタ情報

inarticle



-Python
-

執筆者:


comment

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

関連記事

no image

kaggle Titanic Tutorial – 4

名前から取得できるタイトルを分析に利用してみる。 タイトルは末尾に”.”がついているのでこれを利用して切り出す。 def get_title(name): if ‘.’ in …

no image

selectorとxpathを手軽に取得する方法

スクレイピングをするプログラムを開発するときに対象となる項目を取得するためにselector/xpathで指定する。 Google Chromeではselector/xpath値を簡単に取得できる。 …

no image

RoboBrowserでUser Agentが原因ではねられているとき

RoboBrowserを利用していると通常のブラウザでリクエストした時とは異なりエラーがページが返ってくることが多い。 原因はいくつかあるがまず試したいのはUser-Agentの設定。 RoboBro …

no image

SIGNATE お弁当の需要予測-4

今回はSeabornのpairplotを利用して相関の概要を見てみる。ただし相関を見るためにはデータのクレンジングが必要。 まずはnullデータのヒートマップを確認してみる。 sns.heatmap( …

no image

wordpress-xmlrpc

WordPressへPythonから投稿してみる。 まずは設定から。説明はこちらにある。 https://python-wordpress-xmlrpc.readthedocs.io/en/lates …

2018年2月
« 1月   3月 »
 1234
567891011
12131415161718
19202122232425
262728  

side bar top



アーカイブ

カテゴリー