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

  • 相关阅读:
    第3章 敏捷项目管理概述
    第2章 传统与敏捷方法论
    第1章 敏捷思维—“互联网+”知识工作者必备的DNA
    敏捷项目管理架构(APMF)
    敏捷宣言和准则
    研发工程师如何转型项目经理
    软件门外汉的入门进阶
    [摘录]第五部分 经验谈(2)
    [摘录]第五部分 经验谈(1)
    [摘录]第四部分 教训篇(2)
  • 原文地址:https://www.cnblogs.com/hany-postq473111315/p/12303304.html
Copyright © 2011-2022 走看看