Beginning Python From Novice to Professional(8)-ファイルメソッド

1708 ワード

ファイルメソッド
読み書き:
#!/usr/bin/env python
f = open('somefile.txt','w')
f.write('Hello,')
f.write('World!')
f.close()
f = open('somefile.txt','r')
print f.read(5)
Hello
基本ファイルメソッドを使用します.
#!/usr/bin/env python
f = open(r'somefile.txt')
print f.read()
f.close()
f = open(r'somefile.txt')
for i in range(3):
	print str(i) + ':' + f.readline()
f.close()
import pprint
pprint.pprint(open(r'somefile.txt').readlines())
f = open('somefile.txt','w')
f.write('we
change
this file!') f.close() f = open(r'somefile.txt') print f.read() f.close() f = open(r'somefile.txt') lines = f.readlines() f.close() lines[1] = "changed
" f = open(r'somefile.txt','w') f.writelines(lines) f.close() f = open(r'somefile.txt') print f.read() f.close()
This
is a
Test!

0:This

1:is a

2:Test!

['This
', 'is a
', 'Test!
'] we change this file! we changed this file!
ファイル:
#!/usr/bin/env python
f = open(r'somefile.txt','w')
f.write('First line
') f.write('Second line
') f.write('Third line
') f.close() lines = list(open('somefile.txt')) print lines first,second,third = open('somefile.txt') print first print second print third
['First line
', 'Second line
', 'Third line
'] First line Second line Third line