【问题标题】:When I'm writing to a file deletes everything except the replaced word当我写入文件时会删除除替换单词之外的所有内容
【发布时间】:2017-03-28 20:49:14
【问题描述】:

当我尝试写入文件时,会删除文件中的所有内容,除了我要替换的单词。

这是我的代码:

app.route('/', methods=['POST'])
def writing():
    address_1 = address1()
    address_2 = network1()

    try:
        if request.method =="POST":
            var1 = request.form ['addr1'] 
            var2 = request.form ['addr2']

            changeaddress = [var1, var2]
            address = [address_1, address_2]
            new_var = []
            cur_addr = 0
            new_line = None
            with open('address.txt','r+') as file:
                for line in file:
                    if address[cur_addr] in line:
                        new_line = line.replace(address[cur_addr], changeaddress[cur_addr] + "\n")
                        cur_addr += 1
                    new_var.append(new_line)

            with open('address.txt','w') as file:           
                file.writelines(new_var)

    except BaseException as e:
        print e

    return render_template('addr.html', var1=var1,var2=var2)

这是我的文本文件:

#######
    Address 192.168.0.3
    Address 192.168.0.1 <--- I'm reading this
######
##############
########
    Network 123.123.0.1 <---- I'm reading this

例如,在运行代码后,我将192.168.0.1 替换为1.1.1.1,将123.123.0.1 替换为0.0.0.0,我得到了这个:

Address 1.1.1.1
Network 0.0.0.0

如您所见,它会删除除我替换的内容之外的所有内容。我想得到这样的东西:

#######
    Address 192.168.0.3
    Address 1.1.1.1
######
##############
########
    Network 0.0.0.0

所以我的应用不应该替换我想要替换的行。

【问题讨论】:

    标签: python python-2.7 io


    【解决方案1】:

    您只是将替换的行添加到您编写的列表中。

    正如我在上一个问题中所说,缩进新行,如果那里不清楚,请附加未替换的行。

    if address[cur_addr] in line:
        # replace 
        new_var.append(new_line)
    else:
        # keep 
        new_var.append(line) 
    

    【讨论】:

      猜你喜欢
      • 2017-04-16
      • 1970-01-01
      • 1970-01-01
      • 2022-11-18
      • 2013-12-26
      • 2023-03-13
      • 1970-01-01
      • 2020-07-27
      • 1970-01-01
      相关资源
      最近更新 更多