Python File Operator

基本文件操作
In [1]: f = open('test.txt')
In [2]: f.read()
Out[2]: 'abeen....2010-10-21 20:28:10.303459\nabeen....2010-10-21 23:17:51.120509\nabeen....2010-10-21 23:18:13.574263\n'
In [8]: f.readline()
Out[8]: 'abeen....2010-10-21 20:28:10.303459\n'

//读取所有行,返回数组列表
In [17]: l =f.readlines()
In [18]: l
Out[18]:
['abeen....2010-10-21 20:28:10.303459\n',
 'abeen....2010-10-21 23:17:51.120509\n',
 'abeen....2010-10-21 23:18:13.574263\n']

//调整位置
In [16]: f.seek(0)

In [20]: f = open('test.txt', 'w')
In [22]: f.write("this is a test")
In [25]: f.close()
In [26]: f = open('test.txt', 'r')
In [27]: f.read()
Out[27]: 'this is a test'
In [28]: f.close()

//追加内容
In [30]: f = open('test.txt', 'a')
In [31]: f.write("this is append'\n'")
In [32]: f.close()
In [33]: f = open('test.txt', 'r')
In [34]: f.read()
Out[34]: "this is a testthis is append'\n'"

Python在读取一个文件时,会记住其在文件中的位置
In [35]: f.seek(0)
In [36]: f.read(3)
Out[36]: 'thi'
In [37]: f.tell()
Out[37]: 3

有时可能需要以二进制方式读写文件,比如图片和可执行文件。此时,只要在打开文件的方式参数中增加一个“b”即可
In [40]: f = open('test.txt', 'wb')
In [41]: f.write('asdfasdfasd')
In [42]: f.close()
In [46]: f = open('test.txt', 'rb')
In [47]: f.read()
Out[47]: 'asdfasdfasd'
In [48]: f.close()

使用“os.path”来获取基本信息
In [1]: ls
file_test.py  test.txt

In [2]: fils_status = "test.txt"
In [5]: import os
In [6]: print  os.path.isdir(fils_status)
False
In [9]: print  os.path.isfile(fils_status)
True
In [10]: print  os.path.islink(fils_status)
False
In [11]: print  os.path.ismount(fils_status)
False

目录操作

列出目录下内容
In [15]: for filename in os.listdir('file'):
   ....:     print filename
file_test.py
test.txt

创建目录
In [17]: os.mkdir('abeen')
In [18]: ls
abeen/  file_test.py  test.txt
删除目录
In [19]: os.rmdir('abeen')
In [20]: ls
file_test.py  test.txt
多级目录
In [23]: os.makedirs('l/abeen/xiao/sb')
In [24]: ls
file_test.py  l/  test.txt

In [36]: os.removedirs('l/abeen/xiao/sb')
In [37]: ls
file_test.py  test.txt

对指定类型文件进行操作,用fnmatch
In [33]: for file_name in os.listdir('./'):
   ....:     if fnmatch.fnmatch(file_name, '*.txt'):
   ....:         print file_name
test.txt
In [34]: l = ["aa", "aa.txt", "abeen.img", "shanshan.txt"]
In [35]: l
Out[35]: ['aa', 'aa.txt', 'abeen.img', 'shanshan.txt']
In [36]: fnmatch.filter(l,'*.txt')
Out[36]: ['aa.txt', 'shanshan.txt']
In [37]: fnmatch.filter(l,'[a]*')
Out[37]: ['aa', 'aa.txt', 'abeen.img']

创建“虚拟”文件
可以使用“StringIO”模块来创建文件并将其保存在内存中
StringIO

In [39]: import StringIO
In [40]: f = StringIO.StringIO("this is a test")
In [42]: f.read()
Out[42]: 'this is a test'
In [43]: dir(f)
Out[43]:
['__doc__',
 '__init__',
 '__iter__',
 '__module__',
 'buf',
 'buflist',
 'close',
 'closed',
 'flush',
 'getvalue',
 'isatty',
 'len',
 'next',
 'pos',
 'read',
 'readline',
 'readlines',
 'seek',
 'softspace',
 'tell',
 'truncate',
 'write',
 'writelines']
In [45]: f.close()

cStringIO 应该比 StringIO速度快些吧
In [1]: import cStringIO
In [2]: f = cStringIO.StringIO("test by abeen \n test by abeen")
In [3]: f.readline()
Out[3]: 'test by abeen \n'
In [4]: f.readline()
Out[4]: ' test by abeen'
In [5]: f.seek(0)
In [6]: f.read()
Out[6]: 'test by abeen \n test by abeen'
In [7]: dir(f)
Out[7]:
['__class__',
 '__delattr__',
 '__doc__',
 '__format__',
 '__getattribute__',
 '__hash__',
 '__init__',
 '__iter__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'close',
 'closed',
 'flush',
 'getvalue',
 'isatty',
 'next',
 'read',
 'readline',
 'readlines',
 'reset',
 'seek',
 'tell',
 'truncate']
In [8]: f.close()

[Dynamic Language] Python File Operator相关推荐

  1. [Dynamic Language] Python 静态方法、类方法、属性

    突然发现Python属性是比较有意思的,属性是继承的,先看下面代码: 38 class ABeen(object): 39 def f(self): 40 return "abeen&quo ...

  2. [Dynamic Language] Python os

    os模块中比较有用的部分 1. os.sep 可以取代操作系统特定的路径分割符.    2. os.name字符串指示你正在使用的平台.比如对于Windows,它是'nt',而对于Linux/Unix ...

  3. [Dynamic Language] Python Django: 模型使用

    Django 模型 //创建App应用程序 python manage.py startapp books //建立模型 代码 1 from django.db import models 2 3 # ...

  4. python 示例_带有示例的Python File read()方法

    python 示例 文件read()方法 (File read() Method) read() method is an inbuilt method in Python, it is used t ...

  5. BUG之路2--ubuntu安装uwsgi测试报错:failed to open python file test.py

    心路历程 毫无疑问,又是能让我跳楼的BUG,但是结果都一样,很小的细节,卡我两天时间. BUG过程: 在ubuntu上部署django项目时,需要安装uwsgi服务器.根据教程安装完之后,然后会有一个 ...

  6. python ctypes教程_Python ctypes: Python file object - C FILE * | 易学教程

    可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试): 问题: I am using ctypes to wrap a C-library (which I ...

  7. python File write()方法

    参考文章1:Python File write() 方法 参考文章2:Python中文件的读取和写入操作 参考文章3:python File open()方法

  8. python 示例_带有示例的Python File write()方法

    python 示例 文件write()方法 (File write() Method) write() method is an inbuilt method in Python, it is use ...

  9. flush python_带有示例的Python File flush()方法

    flush python 文件flush()方法 (File flush() Method) flush() method is an inbuilt method in Python, it is ...

最新文章

  1. 不改文件名的情况下上传突破
  2. IDEA工具基本设置
  3. 设置root密码,su与sudo的区别
  4. 搭建DNS域名解析服务器和本地配置HOST文件有什么区别?
  5. Object/DataSet Relational Mapping(对象/数据集关系映射)完整版本下载
  6. DTCC 2019 | 阿里云TSDB: 教你解锁时序时空数据库的种种黑科技
  7. k8s与监控--解读prometheus监控kubernetes的配置文件
  8. MySQL高级知识(五)——索引分析
  9. jsp页面科学计数法显示问题的解决办法
  10. HITS 算法(Hypertext Induced TopicSelection)
  11. 各路由协议防环机制汇总(一)
  12. 【数学建模】CUMCM-2017A CT系统参数标定及成像 思路及部分代码
  13. MariaDB—— 14.存储引擎
  14. 2022-2028全球阿兹夫定片行业市场现状及未来发展趋势
  15. 只能吃土豆的牛牛(二进制枚举)
  16. Linux_clustalW安装及使用(部分)
  17. Day 1 廉颇老矣,尚能饭否?
  18. Python 库pyautogui 0.9.52的下载、安装和使用
  19. [论文总结]:faster cnns with direct sparse convolutions and guided pruning 直接稀疏卷积和引导剪枝
  20. CS224N笔记(四) Lecture 7:循环神经网络RNN的进阶——LSTM与GRU

热门文章

  1. Java IO编程全解(五)——AIO编程
  2. Metasploit(一)--Meterpreter的命令速查表
  3. java native
  4. 守住你的网站:防御DDoS***指南
  5. Belkatalog CMS SQL 注入漏洞(图)
  6. XMLHelper.cs
  7. 腾讯是一只邪恶的小企鹅
  8. BCH链上交易量剧增,超越莱特币
  9. 对《Clojure in Action》第二版的书评与作者问答
  10. 程序员必须知道的几个Git代码托管平台(转)