科学の箱

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

django install

まずはdjangoをインストールする pip install django   Versionを確認する python -m django –version はじめてのプロジェク …

no image

K近傍法でデータを分析

K近傍法の手順 データ読み込み EDA スケーリング K選択前処理 モデル評価 K選択 モデル構築   K近傍法でデータを分析する際にはseabornのpairplotが役に立つ df = …

no image

タプルの操作

タプルはPythonで提供されているデータ構造の一つ。タプルは固定長で変更できない複数の値の集合である。 タプルオブジェクト (tuple object) — Python 3.8.0 ドキュメント …

no image

seleniumでWebElement object is not iterableが出るときの対処方法

iterableなオブジェクトを想定して要素を取得、forループに取り込むと下記のようなWebElement object is not iterableが出る。 結論としては勘違い。 Seleniu …

no image

automated the boring – day7

https://automatetheboringstuff.com/chapter14/ 14章ではcsvとJSONを取り扱う。フォーマットとしては単純であるのに、なぜexcel,word, pdf …

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

side bar top



アーカイブ

カテゴリー