科学の箱

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

scikit-learnで適切なアルゴリズムを選択するためのチートシート

  http://scikit-learn.org/stable/tutorial/machine_learning_map/index.html Related posts:automat …

no image

kaggle Titanic Tutorial – 9

さて今回は少し趣向を変えて別のアルゴリズムを試してみる。 アルゴリズムの試し方はこちらを参考にした。 https://www.kaggle.com/omarelgabry/a-journey-thro …

no image

pyperclipを設定する

pyperclipはpip3経由でインストールする。まずはpip3のインストールから。 https://bootstrap.pypa.io/get-pip.pyからget-pip.pyをダウンロードし …

no image

numpyで配列を抜き出す方法

numpyで配列を抜き出す まず基本となるやり方 arr = np.arange(50).reshape(5,10) arr[1:1,] arr[1:2,]   np.arange(50)で …

no image

Scrapy – Tutorial

Tutorialはこちら https://doc.scrapy.org/en/latest/intro/tutorial.html 特に難しい点はないがいくつかポイント spidersディレクトリはプ …

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

side bar top



アーカイブ

カテゴリー