メインコンテンツまでスキップ

「File」タグの記事が16件件あります

全てのタグを見る

Python: 指定したパスのディレクトリ中のファイル一覧を出力

· 約2分
Yu Sasaki
Enterprise Security Manager / Advisor

あるディレクトリから特定のファイルを検索したい場合、探索対象ディレクトリ内のファイルを全て取得する必要があります。今回は、引数にディレクトリを指すパスを指定することによって、そのディレクトリの内容を取得する関数を2つ示します。

ソースコード

# coding: Shift_JIS
import os # osモジュールのインポート
# os.listdir('パス')
# 指定したパス内の全てのファイルとディレクトリを要素とするリストを返す
files = os.listdir('C:\Python25\')
for file in files:
print file

実行結果の一例

DLLs
Doc
include
Lib
libs
LICENSE.txt
lxml-wininst.log
NEWS.txt
PIL-wininst.log
pysqlite-wininst.log
pysqlite2-doc
python.exe
pythonw.exe
README.txt
Removelxml.exe
RemovePIL.exe
Removepysqlite.exe
Scripts
tcl
Tools
w9xpopen.exe

ワイルドカードでリスティング対象を指定

globモジュールのglob()関数の引数内にワイルドカード「*」を含めることが出来ます。これによって、より手軽に目的のファイルを探索することが出来ます。

ソースコード

# coding: Shift_JIS
import glob
# パス内の全ての"指定パス+ファイル名"と"指定パス+ディレクトリ名"を要素とするリストを返す
files = glob.glob('C:\Python25\*.*') # ワイルドカードが使用可能
for file in files:
print file

os.listdir()と異なり、glob.glob()は取得したファイル文字列には先頭に探査ディレクトリ(引数)のパスが付いています。

実行結果の一例

C:Python25LICENSE.txt C:Python25lxml-wininst.log C:Python25NEWS.txt C:Python25PIL-wininst.log C:Python25pysqlite-wininst.log C:Python25python.exe C:Python25pythonw.exe C:Python25README.txt C:Python25Removelxml.exe C:Python25RemovePIL.exe C:Python25Removepysqlite.exe C:Python25w9xpopen.exe

リファレンス

Python: コマンドライン引数の取得 - sys.argv変数

· 約2分
Yu Sasaki
Enterprise Security Manager / Advisor

コマンドラインで与える引数によってプログラムの挙動を変えたいという場面はよくあります。Python ではコマンドライン引数は sys モジュールの argv 属性に文字列を要素とするリストとして格納されています。そして、リストの先頭要素(sys.argv[0])はスクリプトファイル名となっています。

ソースコード

# coding: Shift_JIS
import sys # モジュール属性 argv を取得するため
argvs = sys.argv # コマンドライン引数を格納したリストの取得
argc = len(argvs) # 引数の個数
# デバッグプリント
print argvs
print argc
print
if (argc != 2): # 引数が足りない場合は、その旨を表示
print 'Usage: # python %s filename' % argvs[0]
quit() # プログラムの終了
print 'The content of %s ...n' % argvs[1]
f = open(argvs[1])
line = f.readline() # 1行読み込む(改行文字も含まれる)
while line:
print line
line = f.readline()
f.close

text.txt

It is meaningless only to think my long further aims idly.
It is important to set my aims but at the same time I should confirm my present condition.
Unless I set the standard where I am in any level, I'll be puzzled about what I should do from now on.

実行結果

引数を指定しない場合

$ python argv01.py
['argv01.py']
1
Usage: # python SCRIPTNAME.py filename

引数を指定した場合

$ python argv01.py text.txt
['argv01.py', 'text.txt']
2
The content of text.txt ...
It is meaningless only to think my long further aims idly.
It is important to set my aims but at the same time I should confirm my present condition.
Unless I set the standard where I am in any level, I'll be puzzled about what I should do from now on.

リファレンス

Python: ファイル、ディレクトリの属性確認(存在、読み込み、書き込み、実行)

· 約1分
Yu Sasaki
Enterprise Security Manager / Advisor

ソースコード

$ python
>>> import os
>>> os.access('/root', os.F_OK)
True
>>> os.access('/root', os.R_OK)
False
>>> os.access('/home', os.R_OK)
True
>>> os.access('/root', os.W_OK)
False
>>> os.access('/root', os.X_OK)
False
>>> exit()
$

os.access()の第1引数には調べるパスを指定し、第2引数には調べる内容を指定します。

第2引数調べる内容
os.F_OK存在するか?
os.R_OK読み込めるか?
os.W_OK書き込めるか?
os.X_OK実行可能か?

上の例は、一般ユーザで実行しているため、/rootの読み書きはできないことを示しています。

リファレンス

Python: CSVファイルに書き込み - csv.writerオブジェクト

· 約2分
Yu Sasaki
Enterprise Security Manager / Advisor

試しにチャット履歴をCSVファイルに保存するという場合の例を取り上げます。まぁ実際はメッセンジャーアプリのXMLファイル等をコンバートして保存する例を持ってきた方が良いのかもしれませんが、そうするとコードが長くなり今記事の焦点が合わなくなるので割愛します。

ソースコード

#!/usr/bin/python
# coding: UTF-8
# CSVファイルに書き込み
import csv # CSVファイルを扱うためのモジュールのインポート
filename = "table02.csv"
writecsv = csv.writer(file(filename, 'w'), lineterminator='n') # 書き込みファイルの設定
writecsv.writerow(['2007/11/12 20:19:18', 'や、こんばんは。']) # 1行(リスト)の書き込み
writecsv.writerow(['2007/11/12 20:19:39', 'おいーす'])
writecsv.writerow(['2007/11/12 20:19:53', '久しぶりだね'])
writecsv.writerow(['2007/11/12 20:20:02', 'そだね。'])
chatable = [['2007/11/12 20:42:58', 'そうだね'],
['2007/11/12 20:43:03', '色々ありがとう'],
['2007/11/12 20:43:12', 'いえ、こちらこそ。'],
['2007/11/12 20:43:21', 'それじゃあまた'],
['2007/11/12 20:43:27', 'うん、またねー。']]
writecsv.writerows(chatable) # 複数行(リストのリスト|テーブル)の書き込み

実行結果 (table02.csv)

2007/11/12 20:19:18,や、こんばんは。
2007/11/12 20:19:39,おいーす
2007/11/12 20:19:53,久しぶりだね
2007/11/12 20:20:02,そだね。
2007/11/12 20:42:58,そうだね
2007/11/12 20:43:03,色々ありがとう
2007/11/12 20:43:12,いえ、こちらこそ。
2007/11/12 20:43:21,それじゃあまた
2007/11/12 20:43:27,うん、またねー。

リファレンス

Python: CSVファイルの読み込み - csv.readerオブジェクト

· 約1分
Yu Sasaki
Enterprise Security Manager / Advisor

ソースコード

#!/usr/bin/python
# coding: UTF-8
# CSVファイルの読み込み
import csv
filename = "table01.csv"
csvfile = open(filename)
print csvfile
for row in csv.reader(csvfile):
print row # 1行のリスト
for elem in row:
print elem, # 行の中の要素
print
csvfile.close()
print csvfile

CSVファイル (table01.csv) (番号,名前)

1,aki
2,hiro
3,norika
4,kaede

実行結果

<open file 'table01.csv', mode 'r' at 0x01BECCC8>
['1', 'aki']
1 aki
['2', 'hiro']
2 hiro
['3', 'norika']
3 norika
['4', 'kaede']
4 kaede
<closed file 'table01.csv', mode 'r' at 0x01BECCC8>

リファレンス

Python: テキストファイルの読み込み - read()、readlines()、readline()メソッド

· 約3分
Yu Sasaki
Enterprise Security Manager / Advisor

以下の読み込み用テキストファイルを用いて、 text.txt

It is meaningless only to think my long further aims idly.
It is important to set my aims but at the same time I should confirm my present condition.
Unless I set the standard where I am in any level, I'll be puzzled about what I should do from now on.

以下のメソッドを用いた場合の処理を書いてみます。

  • read() - ファイルを全て読み込み、その文字列データに対して処理を行う
  • readlines() - ファイルを全て読み込み、1行毎に処理を行う
  • readline() - 1行毎に読み込み、その処理を繰り返す

read() - ファイルを全て読み込み、その文字列データに対して処理を行う

f = open('text.txt')
data1 = f.read() # ファイル終端まで全て読んだデータを返す
f.close()
print(type(data1)) # 文字列データ
lines1 = data1.split('\n') # 改行で区切る(改行文字そのものは戻り値のデータには含まれない)
print(type(lines1))
for line in lines1:
print line
print()

実行結果


It is meaningless only to think my long further aims idly.
It is important to set my aims but at the same time I should confirm my present condition.
Unless I set the standard where I am in any level, I'll be puzzled about what I should do from now on.

readlines() - ファイルを全て読み込み、1行毎に処理を行う

f = open('text.txt')
lines2 = f.readlines() # 1行毎にファイル終端まで全て読む(改行文字も含まれる)
f.close()
# lines2: リスト。要素は1行の文字列データ
for line in lines2:
print(line),
print

実行結果

It is meaningless only to think my long further aims idly.
It is important to set my aims but at the same time I should confirm my present condition.
Unless I set the standard where I am in any level, I'll be puzzled about what I should do from now on.

readline() - 1行毎に読み込み、その処理を繰り返す

f = open('text.txt')
line = f.readline() # 1行を文字列として読み込む(改行文字も含まれる)
while line:
print(line)
line = f.readline()
f.close

実行結果

It is meaningless only to think my long further aims idly.
It is important to set my aims but at the same time I should confirm my present condition.
Unless I set the standard where I am in any level, I'll be puzzled about what Ishould do from now on.

リファレンス

チュートリアル