简体   繁体   中英

string.replace method in python

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?

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)

因为with将在运行文件中包含的所有语句后关闭文件,这意味着content局部变量在第二个循环中将为nil

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.

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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM