NO.10 file

来源:互联网 发布:淘宝12寸兵人 编辑:程序博客网 时间:2024/06/05 18:34
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2017/10/21 13:32
# @author : hezefan
# @file : 6.1.py
'''file的读写'''
importcodecs ##解决文件乱码用的
#打开文件需要几步
#1、open文件
#2、文件操作(读或者写)
#3、关闭文件
x = codecs.open('1.txt')#打开文件
#print(x.read()) #读取文件,输出是字符串类型
text = x.read()
result = text.replace('1','A')#将文件中的所有1换乘A
print(result)
x.close()#关闭文件
print(dir(x))#查看文件的方法

#open(filename,mode)
#open方法中的mode参数有几个需要学习
#r 读
#w 写
#b 二进制传输
#a 追加写入
y =codecs.open('2.txt','ab')
y.write('hello,world!\n')
y.write('I`m {0}!\n'.format('hezefan'))#两个格式赋值复习
y.write('I`m %s!\n'%'so cool!')
y.write('you are so beautiful!\n')
y.close()


#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2017/10/21 14:38
# @author : hezefan
# @file : 6.2.py
'''file的一些方法'''
importcodecs

#readlines 方法:读取文件,把每行的内容当做一个字符串,放在一个list里面。读取文件注意光标的移动,正常不能读两次
x=codecs.open('2.txt','rb')
print(dir(x))
text_list=x.readlines()
print(text_list)
print(text_list[0])
print(text_list[1])
x.close()

#readline 方法:一行一行的读取文件,执行一次度一行。
x=codecs.open('2.txt','rb')
#text_list=x.readline()
print(x.readline())
print(x.readline())
print(x.readline())
print('##'*50)
print(x.next())##打印光标的下一行
x.close()

#write 必须传入字符串
#writelines必须传入列表

y = codecs.open('3.txt','wb')
y.write('hello world!\nmy name is hezefan\n')
print(y.tell())##查看文件里面有几个字符
y.writelines(['aaa\n','bbb\n','ccc\n'])
print(y.tell())
y.seek(0)##将光标移到0的位置
y.write('hahah')##从光标位置开始替换字符,此处替换了前五个字符也就是hello
y.flush()#刷新缓存
print(y.name)#打印文件的名字
print(y.encoding)#查看文件的编码方式
print(y.mode)#查看文件的打开方式
print(y.closed)#查看文件是否关闭
y.close()
print(y.closed)



#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2017/10/24 21:06
# @author : hezefan
# @file : 6.3.py

'''file的with用法'''
importcodecs
withcodecs.open('1.txt','rb')asf: ##将打开文件赋值给f,最后退出缩进自动关闭
print(f.read())
withcodecs.open('1.txt','rb')asf:
forkey,line inenumerate(f):##打印文件每一行的内容
ifkey == 2:
print(line)
print('####'*50)
# linecache
importlinecache
count=linecache.getline('1.txt',3)##取某一行的内容
print(count)


原创粉丝点击