How can I verify if the regex exist in a file without reading ?

francois.rabanel at outscale.com francois.rabanel at outscale.com
Thu Jun 14 12:26:44 EDT 2018


Hi,

Here is my script :

It propose to replace some words in a file with a regular expression.
It create a copy to write on it, and if there isn't an error, it delete the original by the copy with "os.rename" at the end.

My problem is, if I work on a huge file, I'll try to avoid to read the file because it will be crash my computer :) and I would to verify if the regex enter by the user, exist. 

I don't know if it's possible, I'm looking for a solution since few hours... so sorry if the question is easy or wtf :) 


------------------------------------

import re
import os

try:

  path = raw_input('Please enter the path of your file that you want to correct : \n')
  print("------------------------")
  print('Which regex ? \n')
  regex = raw_input('----- : ')
  print('By what ? \n')
  new_word = raw_input('----- : ')

  # Creating copy file
  filenames_regex = re.findall(r'[a-zA-Z0-9]+\.', path)
  filename = filenames_regex[len(filenames_regex)-1]
  new_filename = filename + 'copy.txt'

  # Replace regex by new word line by line on copy file
  with open(path) as rf, open(new_filename, 'w') as wf:
    for line in rf:
      wf.write(re.sub(regex, new_word, line))


except OSError:
  print("Permission denied")
except IOError:
  print("This file doesn't exist")
else:
  os.rename(new_filename, filename + 'txt')




python 2.7.10



Thanks ! 

Best regards,
François.



More information about the Python-list mailing list