科学の箱

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

Pythonで文字列を生成するときの方法についてまとめる

Pythonで文字列を生成するときには様々な方法があるのでまとめる。 まず最も基本となるのは生成したい文字をシングルクォーテーションもしくはダブルクォーテーションで囲む方法である。どちらの方法を使って …

no image

配列の属性を確認

numpyでは生成した配列の中身を確認するための属性が用意されている。 主な属性は以下の通り 次元数を確認:ndarray.ndim 各次元の大きさを確認:ndarray.shape 全部の要素数:n …

no image

カテゴリデータのビジュアル

カテゴリ別データのビジュアル 参考)https://www.kaggle.com/omarelgabry/a-journey-through-titanic?scriptVersionId=44779 …

no image

Python + Slack Bot – 2

Slackのチャネルに投稿するにはChanel IDが必要。 Chanel IDは下記から取得できる。 https://api.slack.com/methods/channels.list/test …

no image

dataframe形式で便利なのはいろいろなメソッドが用意されているから

dataframeにすることのメリットは何かといわれると、dataframeにしたとたんに様々な処理をメソッドで実行できるからである。 例えば値がNaNになっていると、処理を進めるうえでいろいろな問題 …

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

side bar top



アーカイブ

カテゴリー