我試圖用一塊文本替換一小段文本。我希望這塊文本將被替換使用Python的替換功能。我真的很想用sed
來獲得這份工作,但我在Windows機器上。無論如何,這裏是我的腳本,不知道爲什麼文本塊沒有被替換。用文本塊替換特定文本
# Change the current working directory to IDX location
import os
print os.getcwd()
os.chdir(##location of my text files##)
print os.getcwd()
#Read file names
com_line=raw_input("File name please:")
contents=[]
strs = '#DREFIELD IDOL_SOURCE="idol source"\n#DREFIELD IDOL_TAXONOMY="taxonomy data"\n #DREFIELD IDOL_CATEGORY="IDOL_CATEGORY"\n #DREFIELD IDOL_PROMOTION="idol_promotion"\n #DREFIELD IDOL_PROMOTION_TERM="IDOL_PROMOTION_TERM"\n #DREFIELD IDOL_WHATSNEW="IDOL_WHATSNEW"\n #DREFIELD IDOL_SUMMARY="IDOL_SUMMARY"\n #DREFIELD IDOL_URL="IDOL_URL DATA"\n #DREFIELD IDOL_FORMNUMBER="IDOL_FORMNUMBER"\n #DREFIELD IDOL_DESCRIPTION="IDOL_DESCRIPTION DATA"\n#DRESECTION 0\n'
with open(com_line) as f:
contents.append(f.readlines())
f.close
#Writing to file
f2 = open("test.idx", 'w')
for content in contents:
for s in content:
if s == '#DRESECTION 0\n':
s.replace("#DRESECTION 0\n", strs)
f2.write("%s" % s)
f2.close
我測試了這個代碼,它也輸入了條件語句。只是想知道爲什麼有需要的文字#DRESECTION 0\n
不會被替換爲strs
?此外,我正在尋找這樣的操作大型文本文件值得一些演出。有沒有更好的方式閱讀python中的大文本文件?