美文网首页
模块(1)open读取文件

模块(1)open读取文件

作者: Sandra_liu | 来源:发表于2021-06-11 09:26 被阅读0次
#!/usr/bin/env python
#coding=utf-8

import codecs
import time


def open_example(in_file):
    '''
    r: read
    a: append
    w: write
    一次性读取文件中的全部内容
    '''
    file_instance = open(in_file, "r")
    content = file_instance.read()
    file_instance.close()
    print(content)

def open_uft8(in_file):
    '''

    :param in_file:
    :return:
    一次性读取文件中的全部内容
    '''

    file_instance = codecs.open(in_file, encoding="utf-8")
    content = file_instance.read()
    file_instance.close()
    print(content)

def open_uft8_readline(in_file):
    # 执行一次这个函数读取一行
    file_instance = codecs.open(in_file, encoding="utf-8")
    content = file_instance.readline()
    file_instance.close()
    print (content)
def open_uft8_readlines(in_file):
    # 一次性读取文件中的全部内容,放到一个列表里面,每一行是列表中的一个元素
    file_instance = codecs.open(in_file, encoding="utf-8")
    content = file_instance.readlines()
    file_instance.close()
    print (content)
    print(content[0])


def write_uft8(in_file):
    # 写入内容到文件,不换行
    file_instance = codecs.open(in_file, encoding="utf-8",mode="a")
    file_instance.write(u"新的一行"+"\n")
    file_instance.write(u"新的二行"+"\n")

    # 把列表中的所有元素写入到文件,不换行
    file_instance.writelines([u"新的三行",u"新的四行"+"\n"])

    # 把缓存中的数据输出到文件
    file_instance.flush()
    print("I am sleeping")

    time.sleep(20)
    file_instance.close()




if __name__=="__main__":
    # open_example("filexample.txt")
    # open_uft8("filexample.txt")
    write_uft8("filexample.txt")
    # open_uft8_readline("filexample.txt")
    # open_uft8_readlines("filexample.txt")

相关文章

  • 模块(1)open读取文件

  • (八)文件

    1.读取文件的操作---open() 2.创建文件的基本操作: 3.读取文件的状态---os,time模块 4.r...

  • Python基础(31) - 将JSON文档映射成Python对

    将JSON文档映射成Python对象 读取JSON文档 导入json模块 读取文件信息 open('地址','r'...

  • 文件

    文件 *打开文件 open打开'r' 读取文件‘w’ 可写文件 *名片持久化管理系统 *导入os模块给重新命名

  • 文件

    *打开文件open打开'r' 读取文件‘w’ 可写文件 *名片持久化管理系统 *导入os模块给重新命名

  • 大家一起学python(5)

    文件 1.读取文件 1)打开文件 -- with open("path.txt") -- 其中...

  • Python 读取并替换整行文件

    Python 读取并替换整行文件 1、python 读取文件 f = open(input_file_path...

  • python 文件操作

    fp=open("文件路径","方式") 文件读取 文件写入 文件关闭 文件读取写入方式

  • Python基本操作

    1.文件读取与写入 with open(somefile) as f,是比较推荐的读取文件时的字段,可自动关闭文件...

  • Python文件和异常

    文件读取 写入文件 异常处理 存储数据的实例 1、从文件中读取数据 file_reader.py open() 打...

网友评论

      本文标题:模块(1)open读取文件

      本文链接:https://www.haomeiwen.com/subject/lrbheltx.html