2017-08-16 80 views
0

有目錄多個文件擴展名爲.txt,.dox,.qcr等搜尋替換從.txt文件數字符串中的蟒蛇

我需要列出txt文件,搜索&替換文本僅來自每個txt文件。

需要搜索$$ \ d ...其中\ d代表數字1,2,3 ..... 100。需要用xxx替換 。

請讓我知道這個python腳本。

在此先感謝。

-Shrinivas

#created following script, it works for single txt files, but it is not working for txt files more than one lies in directory。 -----

def replaceAll(file,searchExp,replaceExp): 
    for line in fileinput.input(file, inplace=1): 
     if searchExp in line: 
      line = line.replace(searchExp,replaceExp) 
     sys.stdout.write(line) 

#following code is not working, i expect to list out the files start #with "um_*.txt", open the file & replace the "$$\d" with replaceAll function. 

for um_file in glob.glob('*.txt'): 
    t = open(um_file, 'r') 
    replaceAll("t.read","$$\d","xxx") 
    t.close() 

回答

0

試試這個。

​​

在這裏,我們要發送的文件句柄到replaceAll功能,而不是一個字符串。

+0

你好,謝謝你,這是不工作的任何數字「\ d」 ......我的意思是searchExp「$$ \ d」沒有得到換成「 xxx「,同樣的代碼工作時,我使用數字說1,然後replaceExp將$$ 1。 「\ d」並非全球取代數字。 – Shrinivas

+0

@Shrinivas看看吧。 –

0

fileinput.input(...)應該處理一堆文件,並且必須以相應的fileinput.close()結束。所以,你可以任一過程都在一個單一的呼叫:處理每個文件之後

def replaceAll(file,searchExp,replaceExp): 
    for line in fileinput.input(file, inplace=True): 
     if searchExp in line: 
      line = line.replace(searchExp,replaceExp) 
     dummy = sys.stdout.write(line)  # to avoid a possible output of the size 
    fileinput.close()      # to orderly close everythin 


replaceAll(glob.glob('*.txt'), "$$\d","xxx") 

或持續接近的FileInput,而是將其忽略了主要的FileInput功能。

+0

嗨,謝謝,它不適用於任何數字「\ d」...我的意思searchExp「$$ \ d」不會被替換爲「xxx」,相同的代碼工作時,我使用數字說1 ,那麼replaceExp將會是$$ 1。 「\ d」並非全球取代數字。 – Shrinivas

+0

@Shrinivas:如果你想替換正則表達式,你將需要使用re模塊。 –

0

你可以試試這個:

import os 
import re 

the_files = [i for i in os.listdir("foldername") if i.endswith("txt")] 

for file in the_files: 
    new_data = re.sub("\d+", "xxx", open(file).read()) 
    final_file = open(file, 'w') 
    final_file.write(new_data) 
    final_file.close()