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
'\n'

字符串本身就是序列类型,可以直接使用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
'4\x12\x00\x00V\xff\x00\x00ab'
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
'4\x12\x00\x00V\xff\x00\x00ab'
>>> 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
'4\x12\x00\x00V\xff\x00\x00ab'
>>> 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")
'\xd6\xd0\xb9\xfa'
>>>
>>> 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'\u4e2d\u56fd'

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'\u4e2d\u56fd'
>>> 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("")
>>>
>>> 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 递归移动文件或目录树。支持跨文件系统操作

Python之文件与目录的更多相关文章

  1. Python操作文件和目录

    Python操作文件和目录 读写文件比较简单,有一点特别注意就好了 windows下Python默认打开的文件以gbk解码,而一般我们的文件是utf-8编码的,所以如果文本含有中文,就会出现异常或者乱 ...

  2. 【转】Python之文件与目录操作(os、zipfile、tarfile、shutil)

    [转]Python之文件与目录操作(os.zipfile.tarfile.shutil) Python中可以用于对文件和目录进行操作的内置模块包括: 模块/函数名称 功能描述 open()函数 文件读 ...

  3. Python之文件与目录操作及压缩模块(os、shutil、zipfile、tarfile)

    Python中可以用于对文件和目录进行操作的内置模块包括: 模块/函数名称 功能描述 open()函数 文件读取或写入 os.path模块 文件路径操作 os模块 文件和目录简单操作 zipfile模 ...

  4. python获取文件所在目录

    1.执行的python程序获取自己文件所在目录 import os,sys os.chdir(sys.path[0]); dir_name = os.path.abspath(os.path.join ...

  5. Python之文件与目录操作(os、zipfile、tarfile、shutil)

    Python中可以用于对文件和目录进行操作的内置模块包括: 模块/函数名称 功能描述 open()函数 文件读取或写入 os.path模块 文件路径操作 os模块 文件和目录简单操作 zipfile模 ...

  6. 3 Python os 文件和目录

    ile 对象使用 open 函数来创建,下表列出了 file 对象常用的函数: 序号 方法及描述 1 file.close() 关闭文件.关闭后文件不能再进行读写操作. 2 file.flush() ...

  7. python操作文件和目录查看、创建、删除、复制

    python内置了os模块可以直接调用操作系统提供的接口函数,os.name查询的是操作系统,‘nt’表示windows系统 >>> import os >>> o ...

  8. 超全!python的文件和目录操作总结

    文件的基本读写 path = r'C:\Users\Brady\Documents\tmp' with open(path + r'\demo.txt', 'r', encoding='utf-8') ...

  9. python基本操作-文件、目录及路径

    目录 1 前言 2 文件夹操作 2.1 查询操作 2.2 创建操作 2.3 删除操作 2.4 修改操作 3 文件操作 3.1 查询操作 3.2 创建操作 3.3 修改操作 3.4 删除 4 路径操作 ...

随机推荐

  1. PE格式第四讲,数据目录表之导入表,以及IAT表

    PE格式第四讲,数据目录表之导入表,以及IAT表 一丶IAT(地址表) 首先我们思考一个问题,程序加载的时候会调用API,比如我们以前写的标准PE 那么他到底是怎么去调用的? 他会Call 下边的Jm ...

  2. Vue阻止冒泡

    <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" ...

  3. Linux系列教程(二)——Linux系统安装(手把手学安装centos6.8)

    在上一篇博客我们简单的介绍了Linux系统的起源,这篇博客我们将通过图示一步一步教大家如何安装Linux系统.注意这里我们选择安装的Linux系统是其一种发行版本 CentOS,这里给大家普及一个概念 ...

  4. python数据结构之树和二叉树(先序遍历、中序遍历和后序遍历)

    python数据结构之树和二叉树(先序遍历.中序遍历和后序遍历) 树 树是\(n\)(\(n\ge 0\))个结点的有限集.在任意一棵非空树中,有且只有一个根结点. 二叉树是有限个元素的集合,该集合或 ...

  5. struts2使用模型传值

    用户bean package userBeans; public class User { private String username; public String getUsername() { ...

  6. 正六边形网格化(Hexagonal Grids)原理与实现

    在路径规划.游戏设计栅格法应用中,正六边形网格不如矩形网格直接和常见,但是正六边形具有自身的应用特点,更适用于一些特殊场景中,比如旷阔的海洋.区域或者太空.本文主要讲述如何对正六边形进行几何学分析.网 ...

  7. C陷阱和缺陷学习笔记

    这段时间把<C陷阱和缺陷>看了,没时间自己写总结.就转一下别人的学习笔记吧http://bbs.chinaunix.net/thread-749888-1-1.html Chapter 1 ...

  8. 【转】Sizeof与Strlen的区别与联系

    原文地址:http://www.cnblogs.com/carekee/articles/1630789.html 1.sizeof  sizeof(...)是运算符,在头文件中typedef为uns ...

  9. V6厂最新V4版本卡地亚蓝气球大号42mm男表|价格报价|

    大家好!为大家带来一款贵族气质的V6厂卡地亚蓝气球大号42mm男表!众所周知卡地亚品牌给人的印象是非常尊贵.奢华的,而且卡地亚蓝气球系列的表款都有着极高的识别度,而且每一款都是极受欢迎的热门腕表,接下 ...

  10. 愚蠢的遗留BUG

    二次开发本来就是很恶心的事,我竟然是三次开发. 今天遇到一个BUG,上传图片的时候报错了,操作过程很简答,点击上传按钮,选择图片,确定上传,如图: 报错信息很直白,也很奇怪: (为了写博客,把代码回滚 ...