python 修改文本

Python017

python 修改文本,第1张

给你一个思路,具体你自己实现

1,大开文件,放入一个对象fileobject

2,大开一个output文件放入对象outputobject

3,先写入你想修改的前12行

4,使用对象a=fileobject.next()一行一行读取

5,建立一个while循环,并且添加判断当n>12的时候开始写数据outputobject.write(a)。

Python批量修改文本文件内容的方法

Python批量替换文件内容,支持嵌套文件夹

import os

path="./"

for root,dirs,files in os.walk(path):

for name in files:

#print name

if name.endswith(".html"):

#print root,dirs,name

filename=root+"/"+name

f=open(filename,"r")

filecontent=""

line=f.readline()

while line:

l=line.replace(":/arcgis_js_api","/arcgisapi")

filecontent=filecontent+l

line=f.readline()

f.close()

f=file(filename,"w")

f.writelines(filecontent)

f.close()

关于本文给大家介绍的Python批量修改文本文件内容的方法

str类自己就有个replace方法:

| replace(...)

| S.replace (old, new[, count]) ->str

|

| Return a copy of S with all occurrences of substring

| old replaced by new. If the optional argument count is

| given, only the first count occurrences are replaced.

>>>s = "I love ruby"

>>>t = s.replace("ruby", "python")

>>>t

'I love python'

>>>

文件的话可以先把整个文件的内容读到内存里,修改以后再写回去