繁体   English   中英

python中的string.replace方法

[英]string.replace method in python

我是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()

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

宁愿做这样的事情-

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

您正在从文件source读取并也在写入文件。 不要那样做 相反,您应该写入NamedTemporaryFile ,然后在完成写入并关闭它之后在原始文件上rename

尝试这个:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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