2

I am a newbie with python, so kindly excuse for asking basic question.

I am trying to use the string.replace method in python and getting a weird behavior. here is what I am doing:

# passing through command line a file name
with open(sys.argv[2], 'r+') as source:
    content = source.readlines()

    for line in content:
        line = line.replace(placeholerPattern1Replace,placeholerPattern1)
        #if I am printing the line here, I am getting the correct value
        source.write(line.replace(placeholerPattern1Replace,placeholerPattern1))

try:
    target = open('baf_boot_flash_range_test_'+subStr +'.gpj', 'w')
        for line in content:
            if placeholerPattern3 in line:
                print line
            target.write(line.replace(placeholerPattern1, <variable>))
        target.close()

When I am checking the values in the new file, then these are not replaced. I could see that the value of the source is also not changed, but the content had changed, what am I doing wrong here?

4 Answers 4

2

Rather do something like this -

contentList = []
with open('somefile.txt', 'r') as source:
    for line in source:
        contentList.append(line)
with open('somefile.txt','w') as w:
    for line in contentList:
        line = line.replace(stringToReplace,stringToReplaceWith)
        w.write(line)
Sign up to request clarification or add additional context in comments.

Comments

1

Because with will close your file after runing all the statements wrapped within it, which means the content local variable will be nil in the second loop.

Comments

0

You are reading from the file source and also writing to it. Don't do that. Instead, you should write to a NamedTemporaryFile and then rename it over the original file after you finish writing and close it.

Comments

0

Try this:

# Read the file into memory
with open(sys.argv[2], 'r') as source:
    content = source.readlines()
# Fix each line
new_content = list()
for line in content:
    new_content.append(line.replace(placeholerPattern1Replace, placeholerPattern1))
# Write the data to a temporary file name
with open(sys.argv[2] + '.tmp', 'w') as dest:
    for line in new_content:
        dest.write(line)
# Rename the temporary file to the input file name
os.rename(sys.argv[2] + '.tmp', sys.argv[2])

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.