0

I wrote a quick and sloppy python script for my dad in order to read in text files from a given folder and replace the top lines with a specific format. My apologies for any mix of pluses (+) and commas (,). The purpose was to replace something like this:

Sounding: BASF CPT-1          
   Depth:   1.05 meter(s)

with something like this:

Tempo(ms); Amplitude(cm/s)      Valores provisorios da Sismica; Profundidade[m] =  1.05

I thought I had gotten it all resolved until my dad mentioned that all the text files had the last number repeated in a new line. Here are some examples of output:

output sample links - not enough reputation to post more than 2 links, sorry

Here is my code:

TIME    AMPLITUDE  
(ms)


#imports
import glob, inspect, os, re
from sys import argv

#work
is_correct = False
succeeded = 0
failed = 0

while not is_correct:
    print "Please type the folder name: "
    folder_name = raw_input()
    full_path = os.path.dirname(os.path.abspath(__file__)) + "\\" + folder_name + "\\"
    print "---------Looking in the following folder: " + full_path
    print "Is this correct? (Y/N)"
    confirm_answer = raw_input()

    if confirm_answer == 'Y':
        is_correct = True
    else:
        is_correct = False

files_list = glob.glob(full_path + "\*.txt")
print "Files found: ", files_list

for file_name in files_list:
    new_header = "Tempo(ms); Amplitude(cm/s)      Valores provisorios da Sismica; Profundidade[m] ="
    current_file = open(file_name, "r+")
    print "---------Looking at: " + current_file.name
    file_data = current_file.read()
    current_file.close()

    match = re.search("Depth:\W(.+)\Wmeter", file_data)
    if match:
        new_header = new_header + str(match.groups(1)[0]) + "\n"
        print "Depth captured: ", match.groups()
        print "New header to be added: ", new_header
    else:
        print "Match failed!"

    match_replace = re.search("(Sounding.+\s+Depth:.+\s+TIME\s+AMPLITUDE\s+.+\s+)   \d", file_data)
    if match_replace:
        print "Replacing text ..."
        text_to_replace = match_replace.group(1)
        print "SANITY CHECK - Text found: ", text_to_replace
        new_data = file_data.replace(text_to_replace, new_header)
        current_file = open(file_name, "r+")
        current_file.write(new_data)
        current_file.close()
        succeeded = succeeded + 1
    else:
        print "Text not found!"
        failed = failed + 1

    # this was added after I noticed the mysterious repeated number (quick fix)
    # why do I need this?
    lines = file(file_name, 'r').readlines() 
    del lines[-1] 
    file(file_name, 'w').writelines(lines) 

print "--------------------------------"
print "RESULTS"
print "--------------------------------"
print "Succeeded: " , succeeded
print "Failed: ", failed
    #template -- new_data = file_data.replace("Sounding: BASF CPT-1\nDepth:  29.92 meter(s)\nTIME    AMPLITUDE  \n(ms)\n\n")

What am I doing wrong exactly? I am not sure why the extra number is being added at the end (as you can see on the "modified text file - broken" link above). I'm sure it is something simple, but I am not seeing it. If you want to replicate the broken output, you just need to comment out these lines:

    lines = file(file_name, 'r').readlines() 
    del lines[-1] 
    file(file_name, 'w').writelines(lines) 

1 Answer 1

2

The problem is that, when you go to write your new data to the file, you are opening the file in mode r+, which means "open the file for reading and writing, and start at the beginning". Your code then writes data into the file starting at the beginning. However, your new data is shorter than the data already in the file, and since the file isn't getting truncated, that extra bit of data is left over at the end of the file.

Quick solution: in your if match_replace: section, change this line:

current_file = open(file_name, "r+")

to this:

current_file = open(file_name, "w")

This will open the file in write mode, and will truncate the file before you write to it. I just tested it, and it works fine.

3
  • 1
    Ohh, nice explanation. I delete my answer, was on completely the wrong track. Dec 5, 2015 at 7:45
  • @aaron_world_traveler: that fixed it! Thank you. Dec 5, 2015 at 15:09
  • 1
    @ragnarswanson - no problem, my pleasure! Dec 5, 2015 at 16:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.