• Python read和write方法


    Python read和write方法:

    read():

    从文件中读取字符串

    注:Python 字符串可以是二进制数据,而不仅仅是文字。

    语法:

    文件对象.read([count])

    count:打开文件需要读取的字符数

    注:read 函数不使用 count 会尽可能多地读取更多的内容,通常一直读取到文件末尾。

    程序:

    # 打开创建好的 test.txt 文件
    f = open("test.txt",'r')
    # 输出文件所有的内容
    print(f.read())
    # 关闭文件
    f.close()
    # hello,world.
    # hello,world2.
    # hello,world3.
    # hello,world4.
    # hello,world5.
    # hello,world6.
    # hello,world7.
    # hello,world8.
    # hello,world9.
    
    
    
    # 使用 count
    # 打开创建好的 test.txt 文件
    f = open("test.txt",'r')
    # 输出文件的前 11 个字符
    print(f.read(11))
    # ['hello,world.
    ']
    # 关闭文件
    f.close()
    # hello,world

    文件位置:

    tell():

    返回文件内当前指向的位置

    # 使用 count
    # 打开创建好的 test.txt 文件
    f = open("test.txt",'r')
    # 输出文件的前 11 个字符
    print(f.read(11))
    # 返回文件内当前指向的位置
    print(f.tell())
    # 11
    # 关闭文件
    f.close()
    # hello,world

    seek(offset [,from]):

    改变当前文件的位置

      offset:表示要移动的字节数

      from :指定开始移动字节的参考位置。

        0:文件开头

        1:当前位置

        2:文件末尾

    程序:

    # 打开创建好的 test.txt 文件
    f = open("test.txt",'r')
    # 输出文件的前 11 个字符
    print(f.read(11))
    # hello,world
    # 返回文件内当前指向的位置
    print(f.tell())
    # 11
    print(f.seek(0,0))
    # 0
    print(f.tell())
    # 0
    print(f.read(11))
    # hello,world
    # 关闭文件
    f.close()

    write( ):

    将任意字符串写入一个文件中

    注:Python字符串可以是二进制数据 和 文字,换行符(' ') 需要自己添加

    语法:

    文件对象.write(字符串)

    程序:

    # write 方法
    # 打开创建好的 test.txt 文件
    
    f = open("test.txt",'w')
    # 在开头,添加文件内容
    f.write('hey boy')
    
    # 关闭文件
    f.close()

    2020-02-14

  • 相关阅读:
    node.js 版本管理工具 — nvm 下载、安装、配置及使用
    UNION [ All ]使用注意事项
    IDEA无法启动问题
    python + jinja2 + pandas 输出HTML报告
    PGbadger 慢日志分析工具
    密码复杂度策略 密码有效期 登陆失败策略
    postgresql 监控 洞察力
    linux 出错 “INFO: task xxxxxx: 634 blocked for more than 120 seconds.”的3种解决方案
    fsck 命令来修复磁盘
    could not locate a valid checkpoint record
  • 原文地址:https://www.cnblogs.com/hany-postq473111315/p/12303304.html
Copyright © 2020-2023  润新知