首页 > 代码库 > Beginning Python From Novice to Professional (8) - 文件方法
Beginning Python From Novice to Professional (8) - 文件方法
文件方法
读写:
#!/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\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()
This is a Test! 0:This 1:is a 2:Test! ['This\n', 'is a\n', 'Test!\n'] we change this file! we changed this file!文件解包:
#!/usr/bin/env python f = 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 lines first,second,third = open('somefile.txt') print first print second print third
['First line\n', 'Second line\n', 'Third line\n'] First line Second line Third line
Beginning Python From Novice to Professional (8) - 文件方法
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。