1、使用open打开文件后必定要记得调用文件对象的close()方法。好比能够用try/finally语句来确保最后能关闭文件。html
2、须要导入import ospython
3、下面是逐行读取文件内容的三种方法:post
一、第一种方法:spa
f = open("foo.txt") # 返回一个文件对象 line = f.readline() # 调用文件的 readline()方法 while line: print line, # 后面跟 ',' 将忽略换行符 #print(line, end = '') # 在 Python 3 中使用 line = f.readline() f.close()
for line in open("foo.txt"): print line,
4、一次性读取整个文件内容:.net
file_object = open('thefile.txt') try: all_the_text = file_object.read() finally: file_object.close()
一、若是是读取文本code
input = open('data', 'rb')
读固定字节htm
chunk = input.read(100)