python的文件操作

  1、文件读取

    在python中通过read()来读取文件内容并返回为字符串

 1 #打开文件步骤:
 2 #1、open打开文件
 3 #2、对打开文件进行文件操作(读\写)
 4 #、close关闭文件
 5 import codecs
 6 
 7 f=codecs.open('text1')
 8 #codecs用于解决文件内的乱码
 9 text=f.read()
10 print(type(text))
11 result= text.replace('1','a')
12 #替换
13 print(result)
14 print(f.read())
15 #打印读取内容
16 f.close()
读取

  2、写文件

    通过写入的方式打开文件,并通过write()进行写入操作

 1 import codecs
 2 #需要注意:
 3 # r    读操作
 4 # w    写入操作
 5 # b    以二进制的方式操作(读取到的内容为字节)
 6 # a    追加操作
 7 f=codecs.open('text3', 'w')
 8 #通过写(write)的方式打开文件
 9 f.write('aiaiaiaiaiaia\n')
10 f.write('say bye\n')
11 f.write('bye 1  \n')
12 f.close()
写入

  3、with用法

    在使用with时,会自动进行close操作,省略了close()操作

1 with codecs.open('text2','rb') as f:
2     for line,value in enumerate(f ):
3         print(line,value)
4         #按行依次打印
5         if line==3-1:
6             #返回指定行内容
7             print(value)
8             print(f.closed)
9             #是否已关闭文件
with

  4、其他操作

 1 import codecs
 2 file = codecs.open('text5','wb')
 3 # print(dir(file))
 4 file.write('ahahaha\ndasdasdasd\n')
 5 print(file.tell())
 6 file.writelines(['asdasd\n','qweqwe','qweqwe'])
 7 #已列表形式写入
 8 print(file.tell())
 9 #返回字符数量
10 file.seek(0)
11 #覆盖从指定光标位置开始
12 file.write('so cool!!!!!!!!!')
13 print(file.name)
14 print(file.encoding)
15 file.close()
其他

 

posted @ 2017-11-01 01:03  依哈  阅读(127)  评论(0编辑  收藏  举报