zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    动态调用WebService以及传递复杂对象
    2021.1112月 SQL、前端、Java文章学习及资源记录
    字符串导出word
    Dapper 返回存储过程值
    SQL2008 查询XML
    兼容各浏览器的iframe方法
    .net 后台任意设置 控件显示和隐藏就OK
    List 增删该查
    iis 7上发布mvc报错:403.14Forbidden Web 服务器被配置为不列出此目录的内容
    kafka使用入门api2
  • 原文地址:https://www.cnblogs.com/hany-postq473111315/p/12303304.html
Copyright © 2011-2022 走看看