本文共 1802 字,大约阅读时间需要 6 分钟。
1
open 第三个参数是 是否缓冲。False 无缓冲,直接操作硬盘。 True 操作内存,速度快。flash或close 才会更新硬盘数据
>>> f = open('somefile.txt', 'w')>>> f.write("hello. ")7>>> f.write("World!")6>>> f.close()hello. World!
>>> f = open('somefile.txt', 'r')>>> f.read(4)'hell'>>> f.read()'o. World!'不提供数字,读取所有的文件。
2.
seek和tell
>>> f = open('somefile.txt', 'r')>>> f.read(4)'hell'>>> f.read()'o. World!'>>> f=open(r'somefile.txt', 'w')>>> f.write('01234567890123456789')20>>> f.seek(5)5>>> f.write('Hello, World')12>>> f.close()>>> f = open(r'somefile.txt')>>> f.read()'01234Hello, World789'>>> f = open(r'somefile.txt')>>> f.read(3)'012'>>> f.read(2)'34'>>> f.tell()53
file.readline:从当前读到下一个换行符,也包括这个换行符
比如:somefile.readline() 返回 ‘Hello wrold\n’
somefile.readline(5)返回‘Hello’
readlines 读取一个文件的所有行。返回list。
writelines和 readlines 相反。传入一个字符串list。不会增加新行,需自己添加。没有writelien,因为有write。
>>> f = open('somefile.txt','w')>>> f.write('this\n is no\nhaiku')17>>> f.close()this is no haiku
换行符需respect 平台。so.linesep
如果希望不关闭继续使用,但是还想更新到硬盘上,用flash。
>>> import fileinput>>> for line in fileinput.input(filename): process(line)4.迭代文件
>>> f = open('somefile.txt')>>> for line in f: print(line) this is nohaiku有空行:
>>> f = open('somefile.txt')>>> for line in f: print(list(line)) ['t', 'h', 'i', 's', '\n'][' ', 'i', 's', ' ', 'n', 'o', '\n']['h', 'a', 'i', 'k', 'u']>>> f.close()有时没有显式的关闭file,但是只要没有向文件写入内容,不关闭也是可以的。
>>> for line in open('somefile.txt'): print(line) this is nohaiku
>>> f = open('somefile.txt', 'w')>>> f.write('fl\n')3>>> f.write('sl\n')3>>> f.write('tl\n')3>>> f.close()>>> lines = list(open('somefile.txt'))>>> lines['fl\n', 'sl\n', 'tl\n']>>> f,s,t=open('somefile.txt')>>> f'fl\n'>>> s'sl\n'>>> t'tl\n'>>> print(open('somefile.txt'))<_io.TextIOWrapper name='somefile.txt' mode='r' encoding='cp936'>open返回一个迭代器。 print向文件写入内容,会在string后面增加新的行。
转载地址:http://mqmmi.baihongyu.com/