zoukankan      html  css  js  c++  java
  • Python编程

    读文件

    f = open('/Users/michael/test.txt', 'r')  # 读取UTF-8编码的文本文件
    f = open('/Users/michael/gbk.txt', 'r', encoding='gbk') # 读取非UTF-8编码的文本文件,传入encoding参数
    f = open('/Users/michael/gbk.txt', 'r', encoding='gbk', errors='ignore') # errors参数,表示如果遇到编码错误后如何处理
    # 如果文件不存在,open()函数就会抛出一个IOError的错误
    
    f.read() # 一次读取文件的全部内容
    f.read(size) # 每次最多读取size个字节的内容
    f.readline() # 可以每次读取一行内容
    f.readlines() # 一次读取所有内容并按行返回list

    保证读取的文件无论出错与否都能正常的关闭:

    • try...finally...:
    try:
        f = open('/path/to/file', 'r')
        print(f.read())
    finally:
        if f:
            f.close()
    • with(原理同try..finally...,且不用写close())
    with open('/path/to/file', 'r') as f:
        print(f.read())

    写文件(写文件和读文件是一样的,唯一区别是调用open()函数时,传入标识符'w'或者'wb'表示写文本文件或写二进制文件)

    with open('/Users/michael/test.txt', 'w') as f:
        f.write('Hello, world!')

    StringIO(在内存中读写str,操作的只能是str)

    from io import StringIO
    f = StringIO('Hello!
    Hi!
    Goodbye!')
    while True:
        s = f.readline()
        if s == '':
            break
        print(s.strip())

    BytesIO(操作二进制数据)

    from io import BytesIO
    f = BytesIO()
    f.write('中文'.encode('utf-8'))
    print(f.getvalue())
    # b'xe4xb8xadxe6x96x87'
  • 相关阅读:
    percona-toolkit
    美河在线
    http://planet.mysql.com/
    MySQL性能诊断与调优 转
    PDB CDB
    mysql安装三 linux源码安装mysql5.6.22
    Solaris10 下mysql5.5.12的安装
    c# 进程间通信
    C# 进程同步,通信
    有关DotNetBar设计样式和运行时的样式不一致的问题
  • 原文地址:https://www.cnblogs.com/sghy/p/8258679.html
Copyright © 2011-2022 走看看