博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

python入门_6

Posted on 2017-02-15 11:42  天高鹿苑  阅读(93)  评论(0)    收藏  举报

文件操作

假设有下面这样一个文本

I know that the clubs are weapons of war
梅花似战场轰鸣的炮枪
I know that the diamonds mean money for this art
这艺术般游戏里 方块便若到手的金钱
But that's not the shape of my heart
但那不是我红桃(心)的形状

 注意: 打开文件在python3中只能用open(),但python2中还可以用file()

f = open('shape of my heart','r',encoding='utf-8') #打开文件,赋值给变量;文件句柄
first_line = f.readline()  #读取第一行文件
print(first_line)

打开的文件模式

r :read  只读模式 不可写

w:write 只写,不可读

a:append 只能追加写在末尾

 

循环打印出文件内容

count = 0    #计数器 计数字符
for line in f:
    if count ==2:
        print('------')
        count +=1
        continue
    print(line.strip())
  count += 1

 

文件句柄操作方法

tell() 指向句柄的位置,按字符计数

read(5)  从句柄处开始读5个字符

seek(0)  句柄返回0 加数字就是返回的位置

readline() #读出一行

readlines() 按列表把文件读出  比较少用

encoding  打印字符编码 无参数

seekable()判断字符是否可返回

flush()  刷新缓存,把缓存中的文本刷到内存中,手工刷,以防丢失

 

f = open('shape of my heart','r',encoding='utf-8') #打开文件
first_line = f.readline()  #读取第一行文件
print(first_line)

print(f.tell())
print(f.read(5))
print(f.seek(0))
print(f.readlines())
print(f.encoding)
print(f.seekable())
print(f.flush())

 

小插曲之打印进度条

导入sys和time模块,每隔0.2s循环打印出#

import sys,time
for i in range(10):
    sys.stdout.write("#")
    sys.stdout.flush()
    time.sleep(0.2)

 

close() 关闭文件

closed() 判断文件是否关闭 返回true or false

文件的修改 会把源文件覆盖掉

 

 打开文件的模式有:

    r,只读模式(默认)。
    w,只写模式。【不可读;不存在则创建;存在则删除内容;】
    a,追加模式。【可读;   不存在则创建;存在则只追加内容;】

"+" 表示可以同时读写某个文件

    r+,可读写文件。【可读;可写;可追加】
    w+,写读
    a+,同a

"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)

    rU
    r+U

"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)

    rb
    wb
    ab

 文件修改:

f = open("shape of my heart","r",encoding='utf-8')
f_new = open("shape of my heart.new","w",encoding='utf-8')

for line in f:
    if 'shape of my heart' in line:
        line = line.replace('shape of my heart','shape of YOU heart')
    f_new.write(line)
f.close()
f_new.close()