2014年8月13日水曜日

Python part1: opening and writing words in a file

ファイルにある文字列を書き込む。
writing letters into a file.

1. ファイルをオープン ref. p.248
a. ファイルをオープンする。その時にファイルを作る。
wは書き込みモードで、ファイルがなければ新規。
rは読み込みで、ファイルが存在する必要あり。
a 追記モード。ファイルがなければ新規に作成。
open a file/make a file.
b.  1行目は変換指示子で、2行目は任意の変数。ref. p.76 変換指示子のタイプ
%s: strで得られる文字列
%d, i: 10進数の整数
%f: 浮動小数点
%x, X: 整数16進数

f = open ('test-%s.txt' %limit, 'w')

2. int関数で入力した内容のタイプを文字列から数字に変更する。
int, long, float関数等が他にもある。ref. p.54
limit = int(raw_input("Limit: "))

変数を定義している。

3. for 文の意味
for 変数 in コンテナ:
コンテナの要素が順番に取り出され、コンテナの要素がなくなり、falseになれば、for分から抜け出す。
for h in range(16):
     if c > limit:
       break
また、while 分の場合は以下のように記載する。
ref. p.55 
/ 除算:(6/2 = 3), %剰余算(5%2 = 1), ** 累算 (5**2=25)

breakはループを抜け出すため。continueはそれ以降のブロックをスキップするため。
while a <= 10:
 a+=1
 if a % 3 != 0:
  continue
 print a

Result:
3
6
9

4. fileへの書き込み
リストとタプルについて。リ
作成した後にストとタプルはオブジェクトを管理するためのコンテナです。リストとタプルの違いは作成した後に変更出来るかどうか。リストは可能で、タプルは変更不可。
リスト [ object1, object2, ...]
タプル ( object1, object2, ...)

     f.write('IAP-%d,11:00:0%x:%x%x:%x%x,BE%d,,JPorg,JPfolder\n' %(c,h,g,e,b,a,d))

------------------------------------
aw-iap-whitelist.py
------------------------------------
#!/usr/bin/python
a = 0
b = 0
c = 0
d = 1000000
e = 0
g = 0
h = 0

#change
limit = int(raw_input("Limit: "))

f = open ('test-%s.txt' %limit, 'w')
print 'Name,LAN MAC Address,Serial Number,Virtual Controller Name,Group Name,Folder Name'
for h in range(16):
 for g in range(16):
  for e in range(16):
   for b in range(16):
    for a in range(16):
     c = c + 1
     d = d + 1
     if c > limit:
       break
     f.write('IAP-%d,11:00:0%x:%x%x:%x%x,BE%d,,JPorg,JPfolder\n' %(c,h,g,e,b,a,d))
    if c > limit:
     break
   if c > limit:
    break
f.close()

0 件のコメント:

コメントを投稿