ファイルをオープンして内容を出力する

>>> f = open("foo.txt")
>>> for line in f:
...     print(line,end="")
... 
SPAM
Egg
Bacon
Sausage
>>> f.close()

>>> with open("foo.txt") as f:
...     for line in f:
...             print(line,end="")
... 
SPAM
Egg
Bacon
Sausage

ファイルの内容を読み込む

>>> f = open("foo.txt")
>>> f.read()
'SPAM\nEgg\nBacon\nSausage\n'
>>> f.close()

>>> f = open("foo.txt")
>>> f.read(10)
'SPAM\nEgg\nB'
>>> f.close()

ファイルを一行ずつ読み込む

>>> f = open("foo.txt")
>>> f.readline()
'SPAM\n'
>>> f.readline()
'Egg\n'
>>> f.close()

ファイルのすべての行を読み込む

>>> f = open("foo.txt")
>>> f.readlines()
['SPAM\n', 'Egg\n', 'Bacon\n', 'Sausage\n']
>>> f.close()

ファイルの特定の行を読み込む

>>> f = open("foo.txt")
>>> f.readlines()[2]
'Bacon\n'
>>> f.close()

>>> import linecache
>>> linecache.getline("foo.txt",2)
'Egg\n'

ファイルをシークする

>>> f = open("foo.txt")
>>> f.seek(2)
2
>>> f.read()
'AM\nEgg\nBacon\nSausage\n'
>>> f.close()

ファイル中の現在位置を取得する

>>> f = open("foo.txt")
>>> f.seek(2)
2
>>> f.tell()
2
>>> f.read(10)
'AM\nEgg\nBac'
>>> f.tell()
12

ファイルに書き込む

>>> f = open("bar.txt","w")
>>> f.write("SPAM\n")
5
>>> f.close()

>>> f = open("bar.txt","a")
>>> f.write("Egg\n")
4
>>> f.close()

ファイルをコピーする

>>> src = open("foo.txt")
>>> dst = open("bar.txt","w")
>>> for line in src:
...     dst.write(line)
... 
5
4
6
8
>>> dst.close()
>>> src.close()

>>> src = open("foo.txt")
>>> dst = open("bar.txt","w")
>>> contents = src.readlines()
>>> dst.writelines(contents)
>>> src.close()
>>> dst.close()

ファイルを開いているモードを確認する

>>> f = open("bar.txt","w")
>>> f.mode
'w'
>>> f.close()

開いているファイル名を確認する

>>> f = open("foo.txt")
>>> f.name
'foo.txt'
>>> f.close()


タグ:

+ タグ編集
  • タグ:

このサイトはreCAPTCHAによって保護されており、Googleの プライバシーポリシー利用規約 が適用されます。

最終更新:2009年08月01日 22:35