Skip to content Skip to sidebar Skip to footer

Python Using Re Module To Parse An Imported Text File

def regexread(): import re result = '' savefileagain = open('sliceeverfile3.txt','w') #text=open('emeverslicefile4.txt','r') text='09,11,14,34,44,10,11, 2788

Solution 1:

This should do the trick, check comments for explanation about what Im doing here =) Good luck

import re
filename = 'sliceeverfile3.txt'
pattern  = '\d\d,\d\d,\d\d,\d\d,\d\d,\d\d,\d\d'
new_file = []

# Make sure file gets closed after being iteratedwithopen(filename, 'r') as f:
   # Read the file contents and generate a list with each line
   lines = f.readlines()

# Iterate each linefor line in lines:

    # Regex applied to each line 
    match = re.search(pattern, line)
    if match:
        # Make sure to add \n to display correctly when we write it back
        new_line = match.group() + '\n'print new_line
        new_file.append(new_line)

withopen(filename, 'w') as f:
     # go to start of file
     f.seek(0)
     # actually write the lines
     f.writelines(new_file)

Solution 2:

You're sort of on the right track...

You'll iterate over the file: How to iterate over the file in python

and apply the regex to each line. The link above should really answer all 3 of your questions when you realize you're trying to write 'item', which doesn't exist outside of that loop.

Post a Comment for "Python Using Re Module To Parse An Imported Text File"