重学Python - Day 05 - python基础 -> python的文件操作:r、w、a、r+、a+ 、readline、readlines 、flush等常用的文件方法

python学习网 2017-11-10 11:30:02

文件的读操作


 

示例:

 1 print("->文件句柄的获取,读操作:")
 2 
 3 f = open('无题','r',encoding='utf8')
 4 d = f.read()
 5 f.close()
 6 print(d)
 7 
 8 print('->例二:')
 9 f = open('无题','r',encoding='utf8')
10 e = f.read(9)
11 f.close()
12 print(e)
13 #python3中,文件中一个中英文都占位1

运行结果:

->文件句柄的获取,读操作:
昨夜星辰昨夜风
画楼西畔桂堂东
身无彩凤双飞翼
心有灵犀一点通
->例二:
昨夜星辰昨夜风
画

 

文件的写操作


 

知识点:

    1. 写操作前,文件先格式化清空文件

    2.清空操作,在执行open的w方法后,清空

1 print("写的操作,写文件的时候,不能调用读方法,读文件的时候,不能调用写方法")
2 
3 f = open('python','w',encoding='utf8')
4 f.write("I must learn python \nbecause, python is important \n")
5 f.write("java is better?")
6 f.write("maybe") #上面的语句,没有加换行符,所以输出的内容是紧接的
7 f.close()

运行结果:

打开文件后显示如下

I must learn python 
because, python is important 
java is better?maybe

 

文件的append方法


 

语法格式:

f = open('文件名''a','encoding = utf8')

文件这种方法为追加模式:1, 空白文件中,直接从头开始写入内容; 2 有内容的文件,会在末尾开始继续写入内容

示例:

f = open('python','a',encoding='utf8')
f.write("花开又花落")
f.close()

运行结果:

I must learn python 
because, python is important 
java is better?maybe花开又花落

 

readline 和 readlines


 readline是逐行读取

readlines是全文读取

示例:

 1 print("readline方法")
 2 f = open('无题','r',encoding='utf8')
 3 a = f.readline()
 4 print("此时光标位置:",f.tell())
 5 b = f.readline()
 6 print("此时光标位置:",f.tell())
 7 print(a.strip())  #strip是字符串方法中去除空格和换行的方法
 8 print(b.strip())
 9 
10 
11 print("readlines方法,会将每行的内容组成一个列表打印")
12 f = open('无题','r',encoding='utf8')
13 c = f.readlines()
14 print(c)
15 print(id(c))
16 print(id(f))
17 for i in c:
18     print(i.strip())
19 print("遍历方法")
20 f.seek(0)
21 for i in f:
22     print(i.strip())
23 f.close()  #文件的操作中,close()方法一定不能忘记

运行结果:

readline方法
此时光标位置: 23
此时光标位置: 46
昨夜星辰昨夜风
画楼西畔桂堂东
readlines方法,会将每行的内容组成一个列表打印
['昨夜星辰昨夜风\n', '画楼西畔桂堂东\n', '身无彩凤双飞翼\n', '心有灵犀一点通']
37826824
5344280
昨夜星辰昨夜风
画楼西畔桂堂东
身无彩凤双飞翼
心有灵犀一点通
遍历方法
昨夜星辰昨夜风
画楼西畔桂堂东
身无彩凤双飞翼
心有灵犀一点通

 

 

 

文件的tell() 和 seek()方法


 示例:

f = open('无题','r',encoding='utf8')
f.read(4)
print('当前光标位置',f.tell())

f.seek(10)
print('当前光标位置',f.tell())
f.close()

#read时,一个中文算三个字符

运行结果:

当前光标位置 12
当前光标位置 10

 

文件操作之flush方法


 

import sys,time

for i in range(20):
    sys.stdout.write("#")
    sys.stdout.flush()
    time.sleep(1)

 

truncate方法


 

f = open('test','w')
f.write("hello")
f.write("\n")
f.write("python")
f.flush() #这样不用执行close方法,内存中的数据,就会写入到disk
f.close()

f = open('test','a')
f.truncate(2)  #截断方法,光标从2开始往后截取
f.close()

 

 

其他的文件方法: r+ 读写方法

 

阅读(822) 评论(0)