[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, οnerrοr=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自己递归实现文件遍历:
本站所有资源全部来源于网络,若本站发布的内容侵害到您的隐私或者利益,请联系我们删除!
合作方式
Copyright © 2004-2018 https://www.gxlcms.com/. All Rights Reserved.
豫ICP备19030742号