python 数据类型 ---文件一

1.文件的操作流程: 打开(open), 操作(read,write), 关闭(close)

下面分别用三种方式打开文件,r,w,a 模式 . "a"模式将不会覆盖原来的文件内容, 会以追加的形式写入。

f=open("file1.txt","r",encoding="utf-8")  # 默认以 "r" 模式打开

f=open("file2.txt","w",encoding="utf-8")

f=open("file3.txt","a",encoding="utf-8")

2. read, readline, readlines

(1) read() 一次性读出所有文件内容, 并且只能读一次

(2) readline() 一行一行读出文件的内容

(3)readlines() 将以列表的形式读出来

3.高效遍历文件内容, 并在第10行插入一行指定内容

f = open("lyric.txt","r",encoding="utf-8")
count = 0
for line in f:
    if count == 9:
        print("------------------我是分割线-------------------")
        count += 1
        continue
    print(line.strip())
    count +=1

4.tell(), seek() 属性

  tell() 打印光标所在的位置

  seek(数字) 回到“数字” 所示的光标位置

# example

f = open("lyric.txt","r",encoding="utf-8")
print(f.tell()) # 打印光标所在的位置
print(f.readline())
print(f.readline())
print(f.readline())
print(f.tell())
f.seek(0) #回到最初的索引地方
print(f.readline())

5. f.truncate(20)

truncate 方法必须是以"a" 模式打开, 从文件开头开始截断 20 个字符

6. flush 用法 ,可以实时刷新新的内容到硬盘

>>> f = open("test.txt","w")
>>> f.write("this is just for testt\n")
22
>>> f.flush()

 7. 文件的修改, 将文件file1 特定行修改后, 写到另一文件中file1_new

思路:读写文件分离, 读一行,写一行, 当遇到特定的行, 利用字符串replace 替换

f = open('lyric.txt','r',encoding="utf-8")
f_new = open('lyric_modify.txt','w',encoding="utf-8")
for line in f:
    if line.strip() == "我的梦":
       # print(repr(line))
    #if "我的梦" in line:
        line = line.replace("我的梦","Frank's dream")
        f_new.write(line)
    else:
        f_new.write(line)
f.close()
f_new.close()

8. 文件的修改进阶---将参数1 修改为参数2

import sys
f = open("lyric.txt","r",encoding="utf-8")
f_new = open("lyric_2.txt","w",encoding="utf-8")
origi_str = sys.argv[1]
replace_str = sys.argv[2]
for line in f:
    if  origi_str in line:
        line = line.replace(origi_str,replace_str)
    f_new.write(line)
f.close()
f_new.close()

 

posted @ 2016-12-13 23:16  FrankB  阅读(460)  评论(0编辑  收藏  举报