python小指令碼

2021-09-13 11:17:16 字數 1206 閱讀 4957

#匹配文件內容的關鍵字,並取得該關鍵字所在行所有內容

#find the row where need keyword

def getcontent(tfile,sstr):

global keyword

f1 = open(tfile).readlines()

for i,j in enumerate(f1):

if sstr in j:

keyword = linecache.getline(tfile,i+1)[:-1]

getcontent('d:/1.txt','***')

itemnumberex_mir = keyword

#'***'為需要查詢的關鍵字

更簡潔得方式:

#find the row where need keyword

def getcontent(fname, sstr):

f = open(fname)

for line in f.readlines():

if sstr in line:

return line

#將目標文字中所有關鍵字替換為需要的字段

def modifyip(tfile,sstr,rstr):

try:

lines=open(tfile,'r').readlines()

word=open(tfile,'r').readline()

if len(lines) == 1 and login_key != -1:

flen=len(lines)

for i in range(flen):

if sstr in lines[i]:

lines[i]=lines[i].replace(sstr,rstr)

open(tfile,'w').writelines(lines)

elif len(lines) > 1:

flen=len(lines)

for i in range(flen):

if sstr in lines[i]:

lines[i]=lines[i].replace(sstr,rstr)

open(tfile,'w').writelines(lines)

except exception,f:

print f

modifyip('d:/1.txt','替換前的內容','替換後的內容')

小指令碼 小指令碼記錄本

目錄 1 c 計算程式耗時 2 c 計算程式耗時 基於opencv,需要標頭檔案 3 c 讀寫txt檔案 4 c 中執行終端指令 複製 移動檔案等 5 c 建立資料夾 判斷資料夾是否存在,不存在則建立 6 批量刪除資料夾中0位元組的檔案 shell指令碼 include clock t start ...

python檔案命名小指令碼

寫個檔案命名的python程式,復 yu 習一下python。程式寫得應該不是很好。import os import shutil from pil import image 輸入為路徑 命名方式為統一位數數字遞增 單一檔案格式查詢 輸出為 result.txt 檔名,是否為完整 full 完整庫 ...

shell小指令碼

前言 可能這些指令碼看起來很簡單,很多人都不屑於去寫,但是一切複雜的東西都是由乙個個簡單的東西組合起來的。shell的語法比較怪異,和一般的程式語言有很大的區別,真的要多動手去寫才能學會的 1.要求 1.設定變數file的值為 etc passwd 2.依次向 etc passwd中的每個使用者問好...