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. Java面向对象 线程技术--上篇

     Java面向对象   线程 知识概要:                   (1)线程与进程 (2)自定义线程的语法结构 (3)多线程概念理解 (4)多线程状态图 (5)多线程--卖票 (6)同 ...

  2. jS判断浏览器终端

    在做移动端项目的时候,常常会遇到需要判断页面浏览终端的需求.要想判断是什么浏览器终端,先打印 navigator.userAgent 出来.所以收集了几种比较常用的方法: if(/(iPhone|iP ...

  3. 一款好用的软件easyUI

    easyui是一种基于jQuery的用户界面插件集合. easyui为创建现代化,互动,JavaScript应用程序,提供必要的功能. 使用easyui你不需要写很多代码,你只需要通过编写一些简单HT ...

  4. JAVAEE企业级应用开发浅谈第二辑:MVC和三层架构

    上海尚学堂警句:一份信心,一份努力,一份成功:十分信心,十分努力,十分成功. Step1.情景概要 Hello,小伙伴们,昨天跟大家分享了JAVA EE 企业级应用开发中大家耳熟能详的概念-三层架构, ...

  5. Ubuntu Mac OS主题分享

    Ubuntu Mac OS主题分享 一直想搞一个Mac OS主题试试,结果很悲催,在网上搜索的Macbuntu主题在安装主题(macbuntu-os-themes-Its-v7)和 图标(macbun ...

  6. win10 UWP 显示地图

    微软自带的地图很简单 引用地图xmlns:Map="using:Windows.UI.Xaml.Controls.Maps" 写在<Page> 然后在Grid 用Map ...

  7. win10 uwp App-to-app communication 应用通信

    这篇文章都是乱说的,如果觉得有不好的,可以发我邮箱 应用之间需要相互的发送信息,就是我们经常用的分享 有个人看到一个网页很好,于是就希望把这个网页发送到邮件,那么这样的话就是使用应用通信. 因为每个应 ...

  8. 基于Eclipse IDE的Ardupilot飞控源码阅读环境搭建

    基于Eclipse IDE的Ardupilot飞控源码阅读环境搭建 作者:Awesome 日期:2017-10-21 需准备的软件工具 Ardupilot飞控源码 PX4 toolchain JAVA ...

  9. 微信开发-微信JSSDK错误:invalid url domain

    错误类型:invalid url domain 调试返回参数: { "errMsg": "config:invalid url domain" } 截图: 环境 ...

  10. Python练习----购物车

    要求: 1.启动程序后,输入用户名密码后,如果是第一次登录,让用户输入工资,然后打印商品列表 2.允许用户根据商品编号购买商品 3.用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒 4.可随时 ...