zoukankan      html  css  js  c++  java
  • Python之文件与目录

    file

    通常建议使用open()打开文件,file用于类型判断

    如果要把数据写到磁盘上,除调用flush()外,还得用sync(),以确保数据从系统缓冲区同步到磁盘。close()总是会调用这两个方法。

    打开模式:

    *r:只读

    *w:只写。已存在文件将被清除

    *a:添加。总是添加到文件尾部

    *b:二进制模式

    *r+:更新文件,可读写,不会截断文件

    *w+:更新文件,可读写,清除原有内容

    *a+:更新文件,可读写,总是在尾部添加

    后面三种模式之前没有使用过。

    文件对象还实现迭代器协议,可直接循环获取其内容:

    >>> f = open("test.txt","r")
    >>> 
    >>> for line in f:print line
    ... 

    读方法总能判断不同平台的换行标记,但写方法不会添加任何换行字符,包括writelines

    >>> f = open("test.txt","w")
    >>> f.write("a")
    >>> f.writelines("bc")
    >>> f.writelines("bc")
    [root@typhoeus79 guosong]# cat test.txt             
    abcbc[root@typhoeus79 guosong]# 

    如必须按不同平台写入换行标记,可以使用os.linesep

    >>> import os
    >>> os.linesep
    '
    '

    字符串本身就是序列类型,可以直接使用writelines(str)。

    readline()会返回包括换行符在内的整个行数据。

    通常建议用迭代器或者xreadlines() 代替readlines(),因为readlines()默认是一次性读取整个文件。

    binary

    用struct将其他类型构建成二进制字节数组,然后写入文件即可。

    >>> data = struct.pack('i2s','ab')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    struct.error: pack requires exactly 2 arguments
    >>> data = struct.pack("2i2s", 0x1234, 0xFF56, "ab")
    >>> data
    '4x12x00x00Vxffx00x00ab'
    struct.pack(fmt, v1, v2, ...)
    Return a string containing the values v1, v2, ... packed according to the given format. The arguments must match the values required by the format exactly.
    >>> data = struct.pack("2i2s", 0x1234, 0xFF56, "ab")
    >>> 
    >>> 
    >>> data
    '4x12x00x00Vxffx00x00ab'
    >>> open("test.data","w").write(data)

    查看对应的二进制格式:

    在vim中使用命令:%!xxd

    0000000: 3412 0000 56ff 0000 6162 0a              4...V...ab.

    反解:

    >>> import struct
    >>> data = struct.pack("2i2s", 0x1234, 0xFF56, "ab")
    >>> data
    '4x12x00x00Vxffx00x00ab'
    >>> struct.unpack(data)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: unpack expected 2 arguments, got 1
    >>> struct.unpack("2i2s",data) #必须指定格式
    (4660, 65366, 'ab')

    对于相同类型的数据,可以考虑array,以获得更好的性能。

    encoding

    标准库codes提供一个包装版的open(),可自动完成编码转换工作。

    >>> import sys
    >>> sys.getdefaultencoding()#默认的编码为ascii
    'ascii'
    >>> sys.setdefaultencoding("utf-8")#直接设置出错
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'module' object has no attribute 'setdefaultencoding'
    >>> reload(sys) #重新reload即可,原因呢??目前还不清楚,后续更新!!!
    <module 'sys' (built-in)>
    >>> sys.setdefaultencoding("utf-8")
    >>> import codecs
    >>> 
    >>> f = codecs.open("test.txt","w","gbk")
    >>> 
    >>> f.write("中国")
    >>> 
    >>> "中国".encode("gbk")
    'xd6xd0xb9xfa'
    >>> 
    >>> s = codecs.open("test.txt",encoding="gbk").read()
    >>> s
    u''
    >>> print s
    
    >>> f.close() #必须关闭或执行flush,f.write("中国")才刷到磁盘,否则读取的内容为空
    >>> s = codecs.open("test.txt",encoding="gbk").read()
    >>> print s  
    中国
    >>> s
    u'u4e2du56fd'

    test.txt 通过vim命令中%!xxd看到结果为:

    0000000: d6d0 b9fa 0a                             .....
    >>> import sys
    >>> reload(sys)
    <module 'sys' (built-in)>
    >>> sys.setdefaultencoding("utf-8")
    >>> import codecs
    >>> 
    >>> from contextlib import *
    >>> 
    >>> with codecs.open("test.txt","w","gbk") as f: #使用上下文,默认会close,故不需要再手动close
    ...     f.write("中国")
    ... 
    >>> 
    >>> s = codecs.open("test.txt",encoding="gbk").read()
    >>> s
    u'u4e2du56fd'
    >>> print s
    中国

     desciptor

    除使用文件对象外,某些时候还可能需要直接操控文件描述符。

    http://docs.python.org/2.7/library/os.html#open-constants

    >>> import os
    >>> fd = os.open("test.txt",os.O_CREAT | os.O_RDWR,0644)
    >>> 
    [root@typhoeus79 alter_table]# ls -l test.txt 
    -rw-r--r-- 1 root root 0 Oct 16 20:53 test.txt
    >>> import os
    >>> fd = os.open("test.txt",os.O_CREAT|os.O_RDWR,0644) 
    >>> 
    >>> os.write(fd,"abc")
    3
    >>> 
    >>> f = os.fdopen(fd,"r+") #通过描述符创建文件对象
    >>> 
    >>> f.seek(0,os.SEEK_SET) #注意调整位置
    >>> os.SEEK_SET
    0
    >>> f.read()
    'abc'
    >>> f.write("123")
    >>> 
    >>> f.flush()
    >>> 
    >>> os.lseek(fd,0,os.SEEK_SET)
    0
    >>> os.lseek(fd,0,100)        
    >>> os.read(fd,100) 
    'abc123'
    >>> os.close(fd)

    文件对象fileno()方法返回其对应的文件描述符。

    tempfile

    * TemporaryFile:创建临时文件对象,关闭时自动删除

    *NamedTemporaryFile:创建临时文件对象,可获取文件名,参数决定是否自动删除

    *SpooledTemporaryFile:和TemporaryFile类似,只有在数据超过阈值时,才写入硬盘

    http://docs.python.org/2.7/library/tempfile.html#module-tempfile

    >>> import tempfile,os.path
    >>> 
    >>> tmp = tempfile.NamedTemporaryFile()
    >>> 
    >>> tmp.name
    '/tmp/tmprft_9A'
    >>> os.path.exists(tmp.name)
    True
    >>> tmp.close()
    >>> os.path.exists(tmp.name)
    False

    默认使用系统临时目录和前缀,当然也可以指定不同的配置。

    >>> import contextlib
    >>> 
    >>> with tempfile.NamedTemporaryFile(prefix="xxx_",suffix=".tmp",dir=".") as f:
    ...     print f.name
    ... 
    /data1/guosong/code/code_guosong/alter_table/xxx_ukGJ2F.tmp

    与临时文件有关的函数还有:

    *tempfile.gettempdir:返回系统临时文件存放路径

    *tempfile.gettempprefix:返回默认的临时文件名前缀

    *tempfile.mkdtemp:创建临时目录

    *tempfile.mkstemp:创建临时文件,返回描述符和文件名,需手动删除

    *os.tempnam:仅返回有效的临时文件名,并不创建文件

    *os.tmpfile():创建临时文件对象,关闭后自动删除

    >>> tempfile.gettempdir()
    '/tmp'
    >>> 
    >>> tempfile.gettempprefix()
    'tmp'
    >>> 
    >>> d = tempfile.mkdtemp()
    >>> d
    '/tmp/tmpr7Jq64'
    >>> os.removedirs(d)
    >>> d
    '/tmp/tmpr7Jq64'
    >>> os.path.exists(d)
    False

    os.path

    常用函数列表

    http://docs.python.org/2.7/library/os.path.html#module-os.path

    os

    http://docs.python.org/2.7/library/os.html#module-os

    shutil——High-level file operations, including copying.

    http://docs.python.org/2.7/library/shutil.html#module-shutil

    常用函数列表(为啥有这么多函数呢??实际需求驱动??)

    函数  说明
    copyfile

    拷贝文件内容,不包括权限等属性,且目标必须是包含文件名的路径

    copymode

    仅拷贝权限,不包括owner以及文件内容

    copystat

    拷贝权限、时间等属性,不包括owner和内容

    copy

    拷贝文件,包括权限属性。覆盖已有文件,目标可以是目录

    copy2

    拷贝文件,然后调用copystat

    copytree

    拷贝目录树,包括权限等属性

    rmtree

    删除目录树

    move 递归移动文件或目录树。支持跨文件系统操作
  • 相关阅读:
    1
    vim配置
    pyspark
    添加底部小火箭+目录
    00
    博客园代码高亮设置
    01. 枚举类型
    01. 授权问题
    Android Studio打包签名全过程
    linux 阿里云源地址
  • 原文地址:https://www.cnblogs.com/gsblog/p/3371052.html
Copyright © 2011-2022 走看看