Python文件和目录操作详解


Posted in Python onFebruary 08, 2015

一、文件的打开和创建

1、打开

open(file,mode):
>>>fo = open('test.txt', 'r')

>>>fo.read()

'hello\n'

>>>fo.close()

file(file,mode):
>>>f = file('test.txt', 'r')

>>>f.read()

'hello\n'

>>>f.close()

mode可取值:

Python文件和目录操作详解

2、创建

用w/w+/a/a+模式打开即可。

二、文件的读取
1、String = FileObject.read([size])

>>> fr = open('test.txt')

>>> fr.read()

'hello\nworld\n'

or:
>>> for i in open('test.txt'):

...     print i

... 

hello
world

2、String = FileObject.readline([size])
>>> f = open('test.txt')

>>> f.readline()

'hello\n'

>>> f.readline()

'world\n'

>>> f.readline()

''

或者可以用next

3、List = FileObject.readlines([size])

>>> f = open('test.txt')

>>> f.readlines()

['hello\n', 'world\n']

三、文件的写入

1、write(string)

>>> f = open('test.txt', 'a')

>>> f.write('hello\nworld')
#'hello\nworld'

2、writelines(list)

>>> l = ['a','b','c']

>>> f=open('test.txt','a')

>>> f.writelines(l)
#'hello\nworldabc'

注:writelines相当于调用了多次write,不会自动添加换行(\n)符

四、内容查找替换

1、FileObject.seek(offset, mode)

offset:偏移量

mode:
0表示将文件指针指向从文件头部到“偏移量”字节处,
1表示将文件指针指向从文件当前位置向后移动“偏移量”字节,
2表示将文件指针指向从文件尾部向前移动“偏移量”字节。

>>> f=open('test.txt')

>>> f.read()

'hello\nworldabc'

>>> f.read()

''

>>> f.seek(0,0)

>>> f.read()

'hello\nworldabc'

>>> f.close()

2、flush:提交更新,即在文件关闭之前把内存中的内容强制写入文件(一般是文件关闭后写入)

3、文件查找:遍历行进行查找

#!/usr/bin/python

import re
search='hello world'

file='test.txt'

count = 0

f = open(file)

for l in f.readlines():

    li = re.findall(search,l)

    if len(li) > 0:

        count += len(li)

print "Search " + str(count) + " \"" + search + "\""

f.close()

4、文件内容替换:遍历行进行替换

替换到新文件demo:

#!/usr/bin/python
os='hello'

of='test.txt'
rs='ten'

rf='test2.txt'
ofh = open(of)

newl=[]

for l in ofh.readlines():

    nl = l.replace(os,rs)

    newl.append(nl)
rfh = open(rf,'w+')

rfh.writelines(newl)

ofh.close()

rfh.close()

替换到原文件demo:
[server@localserver file]$ cat test.txt 

abc

hello

world

hello world

helloworld

hello hello world

[server@localserver file]$ cat fr.py 

#!/usr/bin/python
os='hello'

file='test.txt'
rs='ten'
f = open(file, 'r+')

s=f.read()

f.seek(0,0)

f.close()

f = open(file, 'w+')

f.write(s.replace(os,rs))

f.close()

[server@localserver file] python fr.py

[server@localserver file]$ cat test.txt 

abc

ten

world

ten world

tenworld

ten ten world

这里采用了重建文件的办法。

或用 fileinput 模块直接在原文件上修改:

#!/usr/bin/python

import fileinput
os='hello'

file='test.txt'
rs='ten'
for line in fileinput.input(file, inplace=True):

    print line.replace(os,rs).replace('\n','')

注意,这里删除了\n是因为print时会写入换行。

五、文件及目录操作

一般是借助OS模块实现

1、mkdir(path[,mode=0777]):创建目录,相当于mkdir

>>>import os

>>>os.mkdir('tt')

2、makedirs(name[, mode=511]):创建多级目录,相当于mkdir -p

3、rmdir(path):删除目录,相当于rm

4、removedirs(path):删除多级目录,相当于rm -rf

5、listdir(path):列出目录中文件和文件夹,相当于ls

6、getcwd():获取当前路径,相当于pwd

7、chdir(path):切换目录,相当于cd

8、rename(src, dst):重命名

9、shutil.copyfile(str,dst):复制文件(要引入shutil模块)

10、path.splitext(filename):获取文件路径和扩展名

>>> import os

>>> fileName, fileExtension = os.path.splitext('/path/to/somefile.ext')

>>> fileName

'/path/to/somefile'

>>> fileExtension

'.ext'

11、walk(top, topdown=True, onerror=None):遍历目录

>>> import os

>>> g = os.walk('a')

>>> g.next()

('a', ['b'], [])

>>> g.next()

('a/b', ['f', 'c'], [])

>>> g.next()

('a/b/f', [], ['3.txt'])

>>> g.next()

('a/b/c', ['d', 'e'], [])

>>> g.next()

('a/b/c/d', [], ['1.txt'])

>>> g.next()

('a/b/c/e', [], ['2.txt'])

walk返回的是一个生成器,生成器中的内容是:当前目录,目录列表,文件列表

python自己递归实现文件遍历:

#!/usr/bin/python

import os
def dirList(path):

    filelist = os.listdir(path)

    fpath = os.getcwd()

    allfile = []

    for filename in filelist:

        filepath = os.path.abspath(os.path.join(path, filename))

        if os.path.isdir(filepath):

            allfile.extend(dirList(filepath))

        else:

            allfile.append(filepath)

    return allfile
files = dirList('a')

print files
Python 相关文章推荐
Python字符串和文件操作常用函数分析
Apr 08 Python
使用httplib模块来制作Python下HTTP客户端的方法
Jun 19 Python
Python实现打印螺旋矩阵功能的方法
Nov 21 Python
python 正确保留多位小数的实例
Jul 16 Python
Python读取excel中的图片完美解决方法
Jul 27 Python
Python里字典的基本用法(包括嵌套字典)
Feb 27 Python
Python 动态变量名定义与调用方法
Feb 09 Python
Pytorch .pth权重文件的使用解析
Feb 14 Python
解决Tensorboard可视化错误:不显示数据 No scalar data was found
Feb 15 Python
Python列表元素删除和remove()方法详解
Jan 04 Python
pandas DataFrame.shift()函数的具体使用
May 24 Python
Python Matplotlib绘制等高线图与渐变色扇形图
Apr 14 Python
Python中操作MySQL入门实例
Feb 08 #Python
Python Web框架Flask下网站开发入门实例
Feb 08 #Python
Python中使用wxPython开发的一个简易笔记本程序实例
Feb 08 #Python
Python常用的日期时间处理方法示例
Feb 08 #Python
Python中使用PIL库实现图片高斯模糊实例
Feb 08 #Python
Python中解析JSON并同时进行自定义编码处理实例
Feb 08 #Python
Python Web框架Flask中使用七牛云存储实例
Feb 08 #Python
You might like
超神学院:鹤熙已踏入神圣领域,实力不比凯莎弱
2020/03/02 国漫
声音就能俘获人心,蕾姆,是哪个漂亮小姐姐配音呢?
2020/03/03 日漫
PHP 5.3 下载时 VC9、VC6、Thread Safe、Non Thread Safe的区别分析
2011/03/28 PHP
PHP 获取远程网页内容的代码(fopen,curl已测)
2011/06/06 PHP
php中stdClass的用法分析
2015/02/27 PHP
详谈php中 strtr 和 str_replace 的效率问题
2017/05/14 PHP
JScript 脚本实现文件下载 一般用于下载木马
2009/10/29 Javascript
各浏览器对link标签onload/onreadystatechange事件支持的差异分析
2011/04/27 Javascript
javascript实现促销倒计时+fixed固定在底部
2013/09/18 Javascript
获取鼠标在div中的相对位置的实现代码
2013/12/30 Javascript
jQuery的cookie插件实现保存用户登陆信息
2014/04/15 Javascript
在JavaScript中使用JSON数据
2016/02/15 Javascript
javaScript给元素添加多个class的简单实现
2016/07/20 Javascript
详解基于webpack&gettext的前端多语言方案
2019/01/29 Javascript
详解Vue 匿名、具名和作用域插槽的使用方法
2019/04/22 Javascript
javascript实现简易数码时钟
2020/03/30 Javascript
JavaScript JSON使用原理及注意事项
2020/07/30 Javascript
[02:49]2014DOTA2电竞也是体育项目! 势要把荣誉带回中国!
2014/07/20 DOTA
用Python写一个无界面的2048小游戏
2016/05/24 Python
基于Linux系统中python matplotlib画图的中文显示问题的解决方法
2017/06/15 Python
最简单的matplotlib安装教程(小白)
2020/07/28 Python
阿迪达斯比利时官方商城:adidas比利时
2016/10/10 全球购物
薇诺娜官方网上商城:专注敏感肌肤
2017/05/25 全球购物
个人自我评价分享
2013/12/20 职场文书
小学生家长评语集锦
2014/01/30 职场文书
社团文化节策划书
2014/02/01 职场文书
毕业生自荐书
2014/02/03 职场文书
老同学聚会感言
2014/02/23 职场文书
出国签证在职证明范本
2014/11/24 职场文书
2015年宣传部部长竞选演讲稿
2014/11/28 职场文书
班主任经验交流材料
2014/12/16 职场文书
财务个人年度总结范文
2015/02/26 职场文书
教师党员个人自我评价
2015/03/04 职场文书
2015年车间管理工作总结
2015/07/23 职场文书
多表查询、事务、DCL
2021/04/05 MySQL
Java Socket实现Redis客户端的详细说明
2021/05/26 Redis