中的所有行[fromString,toString]我想用給定的字符串替換我的文本文件中的某段文本。例如,給出下面的文件內容:替換文件
1
---From here---
2
---To here---
3
我想編寫在以這種方式的格式開始一個python函數:
replaceSection('pathToFile','---From here---\n','---To here---\n','Woo Hoo!\n')
這應該在原始文件更改爲:
1
Woo Hoo!
3
我想出了一個簡單的實現(下圖),但我相信它也有一些缺點,我想知道是否有一個更簡單的實現:
- 的代碼很長,這使得它的理解有點麻煩
- 我遍歷了兩次代碼(而不是就地更換) - 這似乎效率不高
這是同一個實現我會使用我的C++代碼,我想Python有一些隱藏美女,將使實施更加優雅
def replaceSection(pathToFile,sectionOpener,sectionCloser,replaceWith = ''): ''' Delete all the lines in a certain section of the given file and put instead a customized text. Return: None if a replacement was performed and -1 otherwise. ''' f = open(pathToFile,"r") lines = f.readlines() f.close() if sectionOpener in lines: isWrite = True # while we are outside the block and current line should be kept f = open(pathToFile,"w") #Write each line until reaching a section opener # from which write nothing until reaching the section end. for line in lines : if line == sectionOpener: isWrite = False if isWrite: # We are outside the undesired section and hence want to keep current line f.write(line) else: if line == sectionCloser: # It's the last line of the section f.write(replaceWith) ) isWrite = True else: # Current line is from the block we wish to delete # so don't write it. pass f.flush() f.close() else: return -1
也許更適合http://codereview.stackexchange.com – sloth
@ Dominic Kexel - 感謝您的評論。代碼實際上與問題無關,但是隻是回答「你試過了什麼?」並使期望的行爲更清晰。你還認爲它應該轉移到codereview?編輯問題並刪除我的代碼?謝謝! –