python勉強メモ: file

open(filename,mode)

  • mode(省略した時にrとして処理される)
    • w:write
    • r:read
  • テキストファイルを実行しようとするコードと同じフォルダーに置く
  • built-in functions

\n :newline 改行

改行もstringの1として数えられる

stuff="x\n y"

print stuff

x

y

len(stuff)

3

open a file, read every line in the file

xfile = open("mbox.txt")`

count = 0

for yomi in xfile:`

   count = count + 1
    print yomi`

print "line_count:", count

reading the whole file

we can read the whole file (newlines and all) into a sigle string

whole_file = xfile.read()

print whole_file

条件に合う行を探す

特定の文字で始まる行を探しだす

for sgashi in xfile:

    if sagashi.startwith("from:"):

        print sagashi

出力する時、自動的に改行が追加されるので、元々付いている改行符号を取り除かないと、空行ができてしまう。

空白(改行は空白だと認識される)を取り除く

for sgashi in xfile:

    sagashi = sagashi.rstrip()
 
    if sagashi.startwith("from:"):

        print sagashi
  • rstrip()
  • lstrip()
  • strip()

特定の文字の始まりではなければ、飛ばす

for sgashi in xfile:

    sagashi = sagashi.rstrip()
 
    if not sagashi.startwith("from:"):

        continue

     print sagashi

特定の文字を含む行を探す

for sgashi in xfile:

    sagashi = sagashi.rstrip()
 
    if not "@japan" in line:

        continue

     print sagashi