科学の箱

科学・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

スライスとインデックスを組み合わせてデータを抜き出す

行列からデータを取得する際には、インデックスを利用すことはわかった。このインデックスの種類としては整数、スライス、配列、ブーリアンがある。これらを組み合わせて柔軟に配列から要素を抜き出すことができる。 …

no image

jupyterで補完機能をつかう

まずはnbextentionsをインストール conda install -y -c conda-forge jupyter_contrib_nbextensions 次にnbextentionsタブ …

no image

SIGNATE お弁当の需要予測-4

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

no image

kaggle Titanic Tutorial – 4

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

no image

配列を利用した四則演算とuniversal関数

四則演算 import numpy as np arr = np.arange(1,11) arr arr + arr arr * arr arr – 100 arr – arr [/cde] np. …

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

side bar top



アーカイブ

カテゴリー