python day4 ---------------文件的基本操作

1.能调用方法的一定是对象,比如数值、字符串、列表、元组、字典,甚至文件也是对象,Python中一切皆为对象。

1 str1 = 'hello'
2 str2 = 'world'
3 str3 = ' '.join([str1,str2])
4 print(str3)
View Code

2.三种基本的文件操作模式:r(only-read)、w(only-write)、a(append)

对文件进行操作的流程:

     第一,建立文件对象。

     第二,调用文件方法进行操作。

     第三,不要忘了关闭文件。(文件不关闭的情况下,内容会放在缓存,虽然Python会在最后自动把内容读到磁盘,但为了以防万一,要养成关闭文件的习惯)

文件file1

一张褪色的照片,
好像带给我一点点怀念。
巷尾老爷爷卖的热汤面,
味道弥漫过旧旧的后院;
流浪猫睡熟在摇晃秋千,
夕阳照了一遍他咪着眼;
那张同桌寄的明信片,
安静的躺在课桌的里面
(1)r模式
在只读模式下写入内容会报错。
1 f = open('file1','r')
2 f_read = f.read()   #read是逐字符地读取,read可以指定参数,设定需要读取多少字符,无论一个英文字母还是一个汉字都是一个字符。
3 print(f_read)
4 f.close()
1 f = open('file1','r')
2 f_read = f.readline() #readline只能读取第一行代码,原理是读取到第一个换行符就停止。
3 print(f_read)
4 f.close()
View Code
1 f = open('file1','r')
2 f_read = f.readlines() #readlines会把内容以列表的形式输出。
3 print(f_read)
4 f.close()
View Code
1 f = open('file1','r')
2 for line in f.readlines() #使用for循环可以把内容按字符串输出。
3   print(line) #输出一行内容输出一个空行,一行内容一行空格... 因为文件中每行内容后面都有一个换行符,而且print()语句本身就可以换行,如果不想输出空行,就需要使用下面的语句:print(line.strip())
4 f.close()
View Code

(2)w模式

在进行操作前,文件中所有内容会被清空。比如在file1中写入'hello world',程序执行后file1中就只剩下一句'hello world'

1 f = open('file1','w',encoding='utf8')  #由于Python3的默认编码方式是Unicode,所以在写入文件的时候需要调用utf8,以utf8的方式保存,这时pycharm(默认编码方式是utf8)才能正确读取,当读取文件时,文件是utf8格式,pycharm也是utf8,就不需要调用了。
2 f_w = f.write('hello world')
3 print(f_w)  #有意思的是,这里并不打印'hello world',只打印写入多少字符
4 f.close()
View Code

(3)a模式

与w模式不同的是,a模式不会把原来内容清空,而是光标移到内容最后位置,继续写入新内容。比如在最后追加'hello world'

1 f = open('file1','a')
2 f_a = f.write('hello world')
3 print(f_a) #还是会打印写入的字符数
4 f.close()
View Code

打印文件,在'流浪猫睡熟在摇晃秋千'后面加上'helloworld'输出

在r模式时,我们说过用for循环和readlines()输出文件内容,这种输出内容的原理是:打开文件,把全部内容读入内存,然后再打印输入,当文件很大时,这种读取方式就不靠谱了,甚至会使机器崩溃。我们需要及时关闭文件,如下:

 1 f = open('file','r')
 2 data=f.readlines()  #注意及时关闭文件
 3 f.close()
 4  
 5 num = 0
 6 for i in data:
 7   num += 1
 8   if num == 5:
 9     i = ''.join([i.strip(),'hello world']) #不要使用“+”进行拼接
10   print(i.strip())
11 f.close()
View Code

对于大数据文件,要使用下面的方法:

1 num = 0
2 f.close()  #不要过早关闭文件,否则程序不能识别操作句柄f.
3 f = open('file','r')
4 for i in f:  #for内部把f变为一个迭代器,用一行取一行。
5   num += 1
6   if num == 5:
7     i = ''.join([i.strip(),'hello world'])
8   print(i.strip())
9 f.close()
View Code

3.tell和seek

     tell:查询文件中光标位置

     seek:光标定位

 1 f = open('file','r')
 2 print(f.tell())  #光标默认在起始位置
 3 f.seek(10)    #把光标定位到第10个字符之后
 4 print(f.tell())  #输出10
 5 f.close()
 6 ----------------------
 7 f = open('file','w')
 8 print(f.tell())  #先清空内容,光标回到0位置
 9 f.seek(10)    
10 print(f.tell())
11 f.close()
12 ----------------------
13 f = open('file','a')
14 print(f.tell())  #光标默认在最后位置
15 f.write('你好 世界'16 print(f.tell())  #光标向后9个字符,仍在最后位置
17 f.close()
View Code

4.flush 同步将数据从缓存转移到磁盘

示例,实现进度条功能

 1 import sys,time  #导入sys和time模块
 2 for i in range(40):
 3   sys.stdout.write('*')
 4   sys.stdout.flush()  #flush的作用相当于照相,拍一张冲洗一张
 5   time.sleep(0.2)
 6 下面代码也能够实现相同的功能
 7 import time 
 8 for i in range(40):
 9   print('*',end='',flush=True) #print中的flush参数
10   time.sleep(0.2)
View Code

5.truncate 截断

不能是r模式下执行,

w模式下,已经清空所有数据,使用truncate没有任何意义,

a模式下,截断指定位置后的内容

1 f = open('file','a')
2 f.truncate(6) #只显示6个字节的内容(6个英文字符或三个汉字),后面的内容被清空。
View Code

6.光标位置总结

一个汉字两个字节,涉及光标位置的方法有4个:readtellseektruncate

 1 #--------------------------光标总结head-----------------------------------
 2 f = open('file','r')
 3 print(f.read(6)) #6个字符
 4 print(f.tell())  #位置12字节,一个汉字两个字节
 5 f.close()
 6  
 7 f = open('file','r')
 8 f.seek(6)      #6个字节
 9 print(f.tell())
10 f.close()
11  
12 f = open('file','a')
13 print(f.tell())  #光标默认在最后位置
14 f.write('你好 世界')
15 print(f.tell())  #光标向后9个字节,一个汉字两个字节,仍在最后位置 182-->191
16 f.close()
17  
18 f = open('file','a',encoding='utf-8')
19 print(f.truncate(6)) #由于需要光标定位位置,所以也是字节。只显示6个字节的内容(6个英文字母或三个汉字,一个汉字两个字节),后面的内容被清空。
20 f.close()
21 #-----------------------------光标总结end---------------------------------
View Code

7.另外3种模式:r+、w+、a+

      r+:读写模式,光标默认在起始位置,当需要写入的时候,光标自动移到最后

     w+:写读模式,先清空原内容,再写入,也能够读取

     a+:追加读模式,光标默认在最后位置,直接写入,也能够读取。

 1 f = open('file','a')
 2 print(f.tell())  #末尾207位置
 3 f.close()
 4  
 5 f = open('file','r+')
 6 print(f.tell())  #0位置
 7 print(f.readline()) #读取第一行
 8 f.write('羊小羚')   #光标移到末尾207位置并写入
 9 print(f.tell())  #213位置
10 f.seek(0)     #光标移到0位置
11 print(f.readline())  #读取第一行
12 f.close()
View Code

8.修改文件内容

思路:由于数据存储机制的关系,我们只能把文件1中的内容读取出来,经过修改后,放到文件2中。

 1 f2 = open('file2','w',encoding='utf8')  #写入的时候必须加utf8
 2 f1 = open('file','r')
 3 num = 0
 4 for line in f1: #迭代器
 5   num += 1
 6   if num == 5:
 7     line = ''.join([line.strip(),'羊小羚
'])  #里面就是对字符串进行操作了
 8   f2.write(line)
 9 f1.close()
10 f2.close()
View Code

9.with语句

可以同时对多个文件同时操作,当with代码块执行完毕时,会自动关闭文件释放内存资源,不用特意加f.close() ,我们通过下面的示例体会with的用法和好处。

with语句重写8中的代码

1 num = 0
2 with open('file','r') as f1,open('file2','w',encoding='utf8') as f2:
3   for line in f1:
4     num += 1
5     if num == 5:
6       line = ''.join([line.strip(),'羊小羚'])
7     f2.write(line)
View Code

10:

在写小程序的时候搜索看到的,转自:http://www.jb51.net/article/91416.htm

原文地址:https://www.cnblogs.com/zhengyuan/p/8427909.html