1. 程式人生 > >替換文本內容

替換文本內容

一個 nbsp print path 處理 lines ace abs 內容

一個簡單的例子,查看當前文件路徑中的文件,查找有‘bye’字符的行,並修改為‘bye’。

註: else:

file_out.write(line)

這兩行代碼不能少,保證了沒有包含‘bye’字符的行也可以被重新寫入文件中,防止了處理完成後文件中只剩下字符所在行。

#!/usr/bin/python

import os

def chtext(filename):

file_handle = open(filename,‘r‘)

lines = file_handle.readlines()

file_handle.close()

file_out = open(filename,‘w‘)

for line in lines:

if not line:

break

if ‘bye‘ in line:

file_out.write(line.replace(‘bye‘,‘bye‘))

else:

file_out.write(line)

file_out.close()

def chkname():

path=os.path.abspath(".")

print("path is %s" %(path))

filelist = os.listdir(path)

for root,dirname,filename in os.walk(path):

for f in filename:

print("name is: %s" %f)

chtext(os.path.join(root,f))

# object_handle = open(files)

# file_text = object_handle.read()

# print(" %s" %(file_text))

# object_handle.close()

chkname()

替換文本內容