1 f = open('text', 'r') # f是文件句柄 2 data = f.read() # read方法能够加整型参数,是几就读几个字符 3 print(data) 4 f.close()
readline():每次读文件中的一句。缓存
readlines():将整个文件中的字符所有读出,并将其存在一个列表里,列表中的每一个元素是文件中的一句。spa
在读大文件时尽可能不要用readlines,太占用内存。code
1 f = open('text', 'r') 2 a = f.readline() 3 b = f.readline() 4 c = f.readline() 5 d = f.readline() 6 print(a) # my name is Bob 7 print(b) # I am 18 years old 8 print(c) # I like learning 9 print(d) # I have a dog
f = open('text', 'r') lines = f.readlines() print(lines) # ['my name is Bob\n', 'I am 18 years old\n', 'I like learning\n', 'I have a dog']
文件句柄是一个迭代器,能够经过for循环取出迭代器中的值,节约内存,处理效率更高。blog
1 f = open('text', 'r') 2 for i in f: 3 print(i.strip()) 4 # my name is Bob 5 # I am 18 years old 6 # I like learning 7 # I have a dog
1 f = open('text', 'w') 2 f.write('hello world') 3 f.close()
1 f = open('text', 'a') 2 f.write('hello world') 3 f.close()
1 f = open('text', 'r') 2 print(f.tell()) # 0 3 print(f.read(2)) # he 4 print(f.tell()) # 2 5 f.seek(0) 6 print(f.tell()) # 0
1 f = open('text', 'w') 2 f.write('Bob is 32') # 此时文件中并无写入 3 f.flush() # 将刚写入缓存区的内容写入到磁盘中 4 f.close()
1 # r+ :从文章起始位置读,从文章最后写 2 # w+ :从光标后一个字符读,在文章最后写,可是在打开文件时清空文档 3 # a+ :从文章最后读,正常追加
1 with open('text', 'r') as f: 2 num = 0 3 for i in f.readlines(): 4 num += 1 5 if num == 4: 6 i = ''.join([i.strip(), '***']) 7 print(i.strip())
1 with open('text', 'r') as f_read, open('text1', 'w') as f_write: 2 num = 0 # 计数,在符合行数时修改内容 3 for line in f_read: # 遍历f_read中的每行 4 num += 1 # 没遍历一行,计数器加一 5 if num == 4: # 在第四次遍历时,即在第四行时执行if块语句 6 line = 'hello\n' # 当在第四行时将文件的内容改成hello 7 f_write.write(line) # 将处理后的全部字符串写入f_write