zoukankan      html  css  js  c++  java
  • 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
    ")
    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()
  • 相关阅读:
    10 款最佳剪贴板管理器
    悉数美剧《黑客军团》中的黑客工具
    Vim的使用方法
    Mysql跨平台(Windows,Linux,Mac)使用与安装
    Linux下网络故障诊断
    RHEL6.2下挂载光驱安装软件
    MySQL数据库服务器的架设
    Unix如何轻松快速复制
    【Linux基础】Linux常用命令汇总
    博客编号数字密码
  • 原文地址:https://www.cnblogs.com/frankb/p/6173528.html
Copyright © 2011-2022 走看看