2014年8月17日日曜日

Python part4: file open, read lines and find a specific word

find 関数で特定の文字列を含む行をプリントアウトする
for line in f:
 if line.find("line-2") >= 0:

------------------------
file-open2.py
------------------------
#!/usr/bin/python
f = open ('file-test-1.txt', 'r')
f2 = open ('file-test-2.txt', 'w')

for line in f:
 if line.find("line-2") >= 0:
  f2.write(line)
  print line
#  f2.write(line[:-1])
#print f.read()
f2.write('IAP')
f.close()
f2.close()

------------------------
file-test-1.txt
------------------------
a,line-1,c
b,line-23,c
c,line-333a,d
a,line-4444,d
c,line-4a3ac,bb,dd
end

------------------------
Result
------------------------
kurokawa-no-MacBook-Air:Linux taka$ ./file-open2.py
b,line-23,c

0 件のコメント:

コメントを投稿