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
'\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之文件与目录的更多相关文章
- Python操作文件和目录
Python操作文件和目录 读写文件比较简单,有一点特别注意就好了 windows下Python默认打开的文件以gbk解码,而一般我们的文件是utf-8编码的,所以如果文本含有中文,就会出现异常或者乱 ...
- 【转】Python之文件与目录操作(os、zipfile、tarfile、shutil)
[转]Python之文件与目录操作(os.zipfile.tarfile.shutil) Python中可以用于对文件和目录进行操作的内置模块包括: 模块/函数名称 功能描述 open()函数 文件读 ...
- Python之文件与目录操作及压缩模块(os、shutil、zipfile、tarfile)
Python中可以用于对文件和目录进行操作的内置模块包括: 模块/函数名称 功能描述 open()函数 文件读取或写入 os.path模块 文件路径操作 os模块 文件和目录简单操作 zipfile模 ...
- python获取文件所在目录
1.执行的python程序获取自己文件所在目录 import os,sys os.chdir(sys.path[0]); dir_name = os.path.abspath(os.path.join ...
- Python之文件与目录操作(os、zipfile、tarfile、shutil)
Python中可以用于对文件和目录进行操作的内置模块包括: 模块/函数名称 功能描述 open()函数 文件读取或写入 os.path模块 文件路径操作 os模块 文件和目录简单操作 zipfile模 ...
- 3 Python os 文件和目录
ile 对象使用 open 函数来创建,下表列出了 file 对象常用的函数: 序号 方法及描述 1 file.close() 关闭文件.关闭后文件不能再进行读写操作. 2 file.flush() ...
- python操作文件和目录查看、创建、删除、复制
python内置了os模块可以直接调用操作系统提供的接口函数,os.name查询的是操作系统,‘nt’表示windows系统 >>> import os >>> o ...
- 超全!python的文件和目录操作总结
文件的基本读写 path = r'C:\Users\Brady\Documents\tmp' with open(path + r'\demo.txt', 'r', encoding='utf-8') ...
- python基本操作-文件、目录及路径
目录 1 前言 2 文件夹操作 2.1 查询操作 2.2 创建操作 2.3 删除操作 2.4 修改操作 3 文件操作 3.1 查询操作 3.2 创建操作 3.3 修改操作 3.4 删除 4 路径操作 ...
随机推荐
- Java面向对象 IO (三)
Java面向对象 IO (三) 知识概要: (1)IO 流的操作规律 (2)异常日志信息IO处理 ...
- CoreData归纳使用
1.CoreData简介 2.CoreData数据模型 3.CoreData的主要对象 4.使用CoreData实现数据存储 一.CoreData简介 CoreData用做数据持久化,是数据持久化的最 ...
- 一起来学linux:网络命令
首先介绍最基本也是经常用到的命令ifconfig,对应windows中的ipconfig.执行ifconfig会将所有的端口信息都显示出来,包括IP地址,MTU 接收和发送的报文还有HWaddr也就是 ...
- Python学习笔记(八)
Python学习笔记(八): 复习回顾 递归函数 内置函数 1. 复习回顾 1. 深浅拷贝 2. 集合 应用: 去重 关系操作:交集,并集,差集,对称差集 操作: 定义 s1 = set('alvin ...
- pm2用法详解+ecosystem.config
对于后台进程的管理,常用的工具是crontab,可用于两种场景:定时任务和常驻脚本.关于常驻脚本,今天介绍一款更好用的工具:pm2,基于nodejs开发的进程管理器,适用于后台常驻脚本管理,同时对no ...
- 聊聊Vue.js组件间通信的几种姿势
写在前面 因为对Vue.js很感兴趣,而且平时工作的技术栈也是Vue.js,这几个月花了些时间研究学习了一下Vue.js源码,并做了总结与输出. 文章的原地址:https://github.com/a ...
- 【转】PC架构系列:CPU/RAM/IO总线的发展历史!
原文地址:http://blog.csdn.net/xport/article/details/1387928 1. 从 IBM PC XT 架构开始...一开始PC的设计中,CPU/RAM/IO都是 ...
- MyBatis 开发记录
1.在classpath下创建log4j.properties # Global logging configuration log4j.rootLogger=DEBUG, stdout # Cons ...
- LINUX 笔记-scp命令
从本地服务器复制到远程服务器: (1) 复制文件: 命令格式: scp local_file remote_username@remote_ip:remote_folder (2) 复制目录: 命令格 ...
- 深入理解final和static关键字
深入理解final和static关键字 参考:http://blog.csdn.net/qq1028951741/article/details/53418852 final关键字 final关键字可 ...