2016-04-22 55 views
2

我是一個使用python的新手,所以請原諒基本問題。python中的string.replace方法

我想在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() 

當我檢查新文件中的值,然後這些都不會被替換。我可以看到源的價值也沒有改變,但內容已經改變,我在這裏做錯了什麼?

回答

0

您正在讀取文件source並正在寫入。不要這樣做。相反,在完成寫入並關閉它之後,您應該寫入NamedTemporaryFile,然後rename它覆蓋原始文件。

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

因爲with乳寧在其內包裹的所有語句,這意味着content局部變量將在第二循環中nil後,將關閉您的文件。

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]) 
相關問題