用input-python改变文件的一部分

时间:2018-06-05 05:22:23

标签: python python-3.x

在txt文件中,数据写成如下:

  • A1 | Auditorium1 | Prote G
  • A2 | Auditorium1 | Prote G

A1 代表礼堂标签, Auditorium1 代表说明, Prote G 代表地址。现在,我想用新的替换礼堂标签的功能。我想使用输入:

<html>
<head>
<title> Login </title>
<script type='text/javascript'>
var attempt = 3; // Variable to count number of attempts.
// Below function Executes on click of login button.
function validate(){
var username = document.getElementById("jp").value;
var password = document.getElementById("pw").value;
if ( username == "user@gmail.com" && password == "$User123$"){
alert ("Login successfully");
window.location = "success.html"; // Redirecting to other page.
return false;
}
else{
attempt --;// Decrementing by one.
alert("You have left "+attempt+" attempt;");
// Disabling fields after 3 attempts.
if( attempt == 0){
document.getElementById("username").disabled = true;
document.getElementById("password").disabled = true;
document.getElementById("submit").disabled = true;
return false;
}
}
}
</script>
</head>
<body>
<div>
<br><h1>Login</h1>
Email:
<form>
<input id="jp" type="text" name="email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$" required placeholder="Enter you Email">
Password:
<input type="password" id="pw" name="psw" pattern="(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{7,15}$" title="Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters" required>
<br><input type="checkbox" checked="checked"name="remember"> <font>Remember me</font>
<a href="#" style="margin-left:20px"><font>Forgot password?</font></a><br>
<button type="submit" onclick="validate()" ><b>LOGIN<b></button>
</form>
</p>
</div>
</body>

例如,如果我将 A1 作为旧标签输入, A5 作为新标签输入,我可以用以某种方式替换 A1 > A5 而不删除或更改我的文件中的说明和地址?在此之后我尝试在'w'模式下打开文件,所以我可以写,但它删除每一行,'a'模式添加整行而不是更改想要的标签。有没有更简单的方法?

2 个答案:

答案 0 :(得分:4)

你只需要回写一个文件,你可以在与f1相同的行中打开它,然后使用f2.write()为它写一个新行:

def label_change():
    label_old = input("Enter label u wanna change: ")
    label_new = input("Enter new one: ")
    with open("aud.txt","r") as f1, open("aud2.txt", "w") as f2:
        for i in f1.readlines():
            r = i.split("|")
            label = r[0]
            desc = r[1]
            adr = r[2]
            if label_old == label:
                label = label_new
            f2.write(label + "|" + desc + "|" + adr)

为了写入同一文件,您可以将内容保存到列表中并写入:

def label_change():
    label_old = input("Enter label u wanna change: ")
    label_new = input("Enter new one: ")
    contents = []
    with open("aud.txt","r") as f1:
        for i in f1.readlines():
            r = i.split("|")
            label = r[0]
            desc = r[1]
            adr = r[2]
            if label_old == label:
                label = label_new
            contents.append(label + "|" + desc + "|" + adr)
    with open("aud.txt", "w") as f1:
        for line in contents:
            f1.write(line)

答案 1 :(得分:1)

您无法轻松修改文件,更容易编写新文件。如果你只想一次改变一件事,那就行了:

def label_change():
    label_old = input("Enter label u wanna change: ")
    label_new = input("Enter new one: ")
    with open("aud.txt","r") as f1, open("mod_aud.txt","w") as outFile:
        for i in f1.readlines():
            label,desc,adr = i.split("|") # decompose directly
            if label == label_old:
                label = label_new
        outFile.write('|'.join( [label,desc,adr] )

如果你想要更改多个标签,最好阅读所有行,修改直到你开心并再次写回所有行。

您必须将数据保存在一个行列表中 - 并且可以简单地用 A1 替换每一行以相同的行,但以 A2

你也可以在python中重命名/删除:

import os
os.remove(someFileName) # delete a file (your old one)
os.rename(old_name, new_name)

作为事后的想法:

您可以使用

轻松省略拆分部分
for i in fi.readlines():
    if i.startswith(label_old):
        outFile.write(label_new + i[len(label_old):]) # string slicing
    else:
        outFile.write(i)