python中的string.replace方法
我是python的新手,所以请原谅我提出这个基本问题 我试图在python中使用string.replace方法,并得到一个奇怪的行为。以下是我正在做的:python中的string.replace方法,python,string,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(pl
# 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()
#通过命令行传递文件名
以open(sys.argv[2],'r+')作为源:
content=source.readlines()
对于内容中的行:
行=行。替换(placeholerPattern1Replace,placeholerPattern1)
#如果我在这里打印行,我得到的是正确的值
source.write(line.replace(placeholerPattern1Replace,placeholerPattern1))
尝试:
目标=打开('baf\U启动\U闪存\U范围\U测试\u'+subStr+'.gpj','w')
对于内容中的行:
如果将HolerPattern3放置在一行中:
打印行
target.write(line.replace(placeholerPattern1,))
target.close()
当我检查新文件中的值时,这些值不会被替换。我可以看到源代码的值也没有更改,但内容已经更改,我在这里做错了什么?您正在从文件
源代码读取并向其写入内容。不要那样做。相反,您应该先向a写入,然后在完成写入并关闭原始文件后将其覆盖到原始文件上。您应该这样做-
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
将在运行包在其中的所有语句后关闭文件,这意味着内容
局部变量将在第二个循环中为nil
。尝试以下操作:
# 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])