python中的string.replace方法

时间:2016-04-22 05:36:53

标签: python string

我是python的新手,请求提出基本问题。

我试图在python中使用string.replace方法并获得一个奇怪的行为。这就是我在做的事情:

# 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()

当我检查新文件中的值时,不会替换它们。我可以看到源的价值也没有改变,但内容已经改变了,我在这里做错了什么?

4 个答案:

答案 0 :(得分:2)

而是做这样的事情 -

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)

答案 1 :(得分:1)

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

答案 2 :(得分:0)

您正在阅读文件<div class='container'> <div class='panel panel-default'> <div class='panel-heading'> <div class='panel-heading text-center'> <h4>Present Schedule<button class='btn pull-right btn-danger' onclick="location.href='past_sched.php'">Go to Past Schedule</button></h4> </div> </div> </div> </div> 并正在写信给它。不要那样做。相反,在完成编写并关闭它之后,您应该写入NamedTemporaryFile然后rename覆盖原始文件。

答案 3 :(得分:0)

试试这个:

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