Beginning Python From Novice to Professional (8) - 文件方法

来源:互联网 发布:音频矩阵干嘛的 编辑:程序博客网 时间:2024/04/19 10:15

文件方法

读写:

#!/usr/bin/env pythonf = 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 pythonf = 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 pprintpprint.pprint(open(r'somefile.txt').readlines())f = open('somefile.txt','w')f.write('we\nchange\nthis 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\n"f = open(r'somefile.txt','w')f.writelines(lines)f.close()f = open(r'somefile.txt')print f.read()f.close()
Thisis aTest!0:This1:is a2:Test!['This\n', 'is a\n', 'Test!\n']wechangethis file!wechangedthis file!
文件解包:

#!/usr/bin/env pythonf = open(r'somefile.txt','w')f.write('First line\n')f.write('Second line\n')f.write('Third line\n')f.close()lines = list(open('somefile.txt'))print linesfirst,second,third = open('somefile.txt')print firstprint secondprint third
['First line\n', 'Second line\n', 'Third line\n']First lineSecond lineThird line

1 0
原创粉丝点击