zoukankan      html  css  js  c++  java
  • 笔记3

    文件读写

    Python内置了读写文件的函数,用法和C是兼容的。
    在磁盘上读写文件的功能都是由操作系统提供的,现代操作系统不允许普通的程序直接操作磁盘,所以,读写文件就是请求操作系统打开一个文件对象(通常称为文件描述符),然后,通过操作系统提供的接口从这个文件对象中读取数据(读文件),或者把数据写入这个文件对象(写文件)。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    # 打开文件,r表示read,w为write,a为append,b为binary
    # 文件不存在则抛出IOError
    f = open('E:Pythonmyapp.log', 'r')
    f = open('E:Pythonmyapp.log', 'rb')
    f = open('E:Pythonmyapp.log', 'r', encoding='gbk')
    f = open('E:Pythonmyapp.log', 'r', encoding='gbk', errors='ignore')

    # 读文件
    f.read() # 一次性读取文件的全部内容到内存
    f.readline() # 一次读取一行
    f.read(size) # 每次最多读取size个字节
    f.readlines() # 一次读取所有内容并按行返回list

    # 写文件
    f.write('Hello, world!')

    # 写入数据,清空缓冲区
    f.flush()

    # 把文件指针归零
    f.seek(0)

    # 关闭文件
    f.close() # 调用此方法,系统才保证把数据全写入文件

    捕捉异常:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    try:
    f = open('/path/to/file', 'r')
    print(f.read())
    finally:
    if f:
    f.close()

    # 等效的简单写法,不必调用close()
    with open('/path/to/file', 'r') as f:
    print(f.read())

    有个read()方法的对象,在Python中统称为file-like Object


    StringIO和BytesIO

    StringIO:在内存中读写str

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    from io import StringIO

    f = StringIO()

    # 写入
    f.write('hello')
    f.write(' ')
    f.write('world!')

    # 获得写入后的str
    f.getvalue() # hello world!

    ####----------------------------------
    from io import StringIO

    # 用一个str初始化StringIO
    f = StringIO('Hello! Hi! Goodbye!')

    # 读取
    while True:
    s = f.readline()
    if s == '':
    break
    print(s.strip())

    BytesIO:在内存中读写bytes

    1
    2
    3
    4
    5
    6
    7
    8
    9
    from io import BytesIO
    f = BytesIO()
    f.write('中文'.encode('utf-8')) # 写入UTF-8编码的bytes
    f.getvalue()

    # 用一个bytes初始化BytesIO
    f = BytesIO(b'xe4xb8xadxe6x96x87')
    # 读取
    f.read()

    操作文件和目录

    os模块,代表 操作系统(operating system),包含非常多的函数用于获取(和修改)本地目录、文件进程、环境变量等的信息。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    import os

    # 操作系统的类型
    os.name
    '''
    posix ====> Linux、Unix或Mac OS X
    nt ====> Windows系统
    '''

    # 环境变量
    os.environ
    '''
    environ({'PSMODULEPATH': 'C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\', 'COMMONPROGRAMW6432': 'C:\Program Files\Common Files'.....
    '''
    # 获取某个环境变量的值
    os.environ.get('PATH')
    os.environ.get('x', 'default')
    s = os.getenv('PATH')

    #################################################
    # -------------------目录操作-------------------#
    #################################################

    # 获取当前工作目录 get current working directory
    os.getcwd()

    # 改变当前目录 change directory, 可以用相对路径
    os.chdir('/Users/pilgrim/diveintopython3/examples')

    # 查看当前工作目录的绝对路径:
    os.path.abspath('.')

    # 拼接路径,此方法可以正确处理不同操作系统的路径分隔符
    # 合并、拆分路径的函数并不要求目录和文件要真实存在,它们只对字符串进行操作
    os.path.join('F:\PythonWorkspace', 'NewDir')

    # expanduser函数用来将包含~符号(表示当前用户Home目录)的路径扩展为完整的路径
    os.path.expanduser("~/.pythonrc")
    # eg:
    os.path.join(os.path.expanduser('~'), 'diveintopython3', 'examples', 'humansize.py')

    # 创建新目录
    os.mkdir('F:\PythonWorkspace\NewDir')

    # 删除目录:
    os.rmdir('F:\PythonWorkspace\NewDir')

    # 拆分路径,此方法可以正确处理不同操作系统的路径分隔符
    os.path.split('F:\PythonWorkspace\file.txt') # ('F:\PythonWorkspace', 'file.txt')

    # 获取文件扩展名
    os.path.splitext('F:\PythonWorkspace\file.txt') # ('F:\PythonWorkspace\file', '.txt')

    # 重命名文件:
    os.rename('test.txt', 'test.py')

    # 删掉文件:
    os.remove('test.py')

    # os模块中不存在复制文件的函数,原因是复制文件并非由操作系统提供的系统调用。可以使用shutil模块的copyfile()函数

    # 列出当前工作目录下的所有目录
    # listdir()只返回文件名,不包含完整路径
    # 不在当前目录下时,isdir必须加上路径,如果只传入文件夹名字,它会在当前工作目录下搜索是否存在此文件夹
    [x for x in os.listdir('.') if os.path.isdir(x)]

    # 列出所有的.py文件
    [x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1]=='.py']

    获取文件元信息

    元信息: 创建时间,最后修改时间,文件大小等等

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    import os
    import time

    # os.stat() 函数返回一个包含多种文件元信息的对象
    metadata = os.stat('feed.xml')

    # 最后修改时间,从纪元(1970年1月1号的第一秒钟)到现在的秒数
    metadata.st_mtime

    # time.localtime() 函数将从纪元到现在的秒数转换成包含年、月、日、小时、分钟、秒的结构体。
    time.localtime(metadata.st_mtime)
  • 相关阅读:
    confluence文档添加右侧浮动导航
    关于惊群问题
    stun server list
    linux 相关代码路径备忘。
    test
    Linux Kernel Packet Traveling
    socketio的静态文件路由处理。
    防蓝光镜片
    Less(21)Cookie Injection- Error Based- complex
    Less(20)POST
  • 原文地址:https://www.cnblogs.com/1659666966/p/9241501.html
Copyright © 2011-2022 走看看