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 路径操作 ...
随机推荐
- Philosophy is systematic reflective thinking on life.
1. perfect coding 逻辑思维.抽象思维.发散思维 knowledge application design 2. Java Object: h ...
- .NET采集数据,放入数据库总结
第一次做采集Json的还简单一些但是XML的简直了......... JSON //采集数据 public string GetBetRecordToRepository()//随便你返回什么 { t ...
- elasticsearch+kibana+metricbeat安装部署方法
elasticsearch+kibana+metricbeat安装部署方法 本文是elasticsearch + kibana + metricbeat,没有涉及到logstash部分.通过beat收 ...
- spring-data-jpa 中,如果使用了one-to-many , many-to-one的注释,会在Jackson进行json字符串化的时候出现错误
问题: spring-data-jpa 中,如果使用了one-to-many , many-to-one的注释,会在Jackson 2.7.0 进行json字符串化的时候出现错误. 解决办法: 通过在 ...
- Chrome等浏览器下出现net::ERR_BLOCKED_BY_CLIENT的解决办法
当我们在做开发时,调试页面图片会出现部分图片无法正常显示,并且确认图片的地址正确: 按F12 Debug查看报错原因,提示net::ERR_BLOCKED_BY_CLIENT错误,但当我们点击图片地址 ...
- 损失函数&经验函数
损失函数:度量模型一次预测的好坏 经验函数:度量模型平均意义下的预测好坏 输出预测值F(x)与实际值Y可能不一致也可能一致,损失函数(Loss function)可以度量一次预测,记作L(Y,F(x) ...
- C# To C++ Converter Cracked ( 破解版 )
C# To C++ Converter v17.10.2 Cracked By X-Cracker 简介 C# To C++ Converter是一款将C#代码或者项目转换为C++的工具 免费版本一次 ...
- [在线Demo]使用Hibernate多租户实现SaaS服务
上一篇文章 基于Hibernate实现多租户(Multi-Tendency)功能简单介绍了利用Hibernate的多租户功能提供SaaS服务的方法,但其中有很多不足,后来都得到了解决. 我尝试过抽取实 ...
- 【ASP.NET MVC 学习笔记】- 20 ASP.NET Web API
本文参考:http://www.cnblogs.com/willick/p/3441432.html 1.ASP.NET Web API(本文简称Web API),是基于ASP.NET平台构建REST ...
- JS的基本类型(小知识)
一:js中的基本类型: 基本类型:boolen, string ,number,null,undefined 引用类型:object,和函数 二.undedifned和null的区别: 1 undef ...