2013-03-05 68 views
0

我写了下面的脚本以匿名电子邮件地址的txt文件:如何在所有目录执行python脚本

import io, os, sys 
import re 

def main(): 

try: 
    # Open the file. 
    myfile = open('emails.txt', 'r') 

    # Read the file's contents. 
    content = myfile.read() 
    content = re.sub(r'.+([email protected]+\.(com|edu))', "xxxx", content) 

    myfile = open('emails.txt', 'w') 
    myfile.write(content) 
    # Close the file. 
    myfile.close() 

except IOError: 
    print('An error occured trying to read the file.') 

except: 
    print('An error occured.') 

main() 

我不知道我怎么会做这项工作的所有目录中的文件及其子目录。

+0

退房这个问题:http://stackoverflow.com/questions/120656/directory-listing-in-python – 2013-03-05 07:57:05

+0

你没有使用io,os或sys – joaquin 2013-03-05 07:58:35

+0

是的,我意识到我并不需要那些 – user2063763 2013-03-05 07:59:08

回答

1

os.walk()是你想要的。我更改了代码片段演示:

#!/usr/bin/env python 

import re 
from os import walk 
from os.path import join 

def main(): 
    for (dirpath, _, filenames) in walk('/path/to/root'): 
     for filename in filenames: 
      # Build the path to the current file. 
      path_to_file = join(dirpath, filename) 
      content = None 
      # Open the file. 
      with open(path_to_file, 'r') as myfile: 
       print 'Reading {0}'.format(path_to_file) 
       # Read the file's contents. 
       content = myfile.read() 
       content = re.sub(r'.+([email protected]+\.(com|edu))', "xxxx", content) 

      with open(path_to_file, 'w') as myfile: 
       myfile.write(content) 

main() 
+0

谢谢,我错过了“path_to_file = join(dirpath,filename)”。所以它只适用于当前目录,而不适用于内部目录。 – user2063763 2013-03-06 01:12:59

0

使用glob.glob

import io, os, sys 
import re 
import glob 

def main(): 
    try: 
     # Open the file. 
     for f in glob.iglob('/path/to/root/*'): 
      if not os.path.isfile(f): 
       continue 
      myfile = open(f, 'r') 

      # Read the file's contents. 
      content = myfile.read() 
      content = re.sub(r'.+([email protected]+\.(com|edu))', "xxxx", content) 

      myfile = open(f.replace('.txt', '.new.txt'), 'w') 
      myfile.write(content) 
      # Close the file. 
      myfile.close() 

     except IOError: 
      print('An error occured trying to read the file.') 
     except: 
      print('An error occured.') 

main() 
+0

谢谢,glob.glob的用法很好理解。 – user2063763 2013-03-06 01:13:40