检查文本文件中的列表是否已存在并附加到其中

时间:2016-01-30 10:11:39

标签: python list append

所以从这个:

Lucy:4
Henry:8
Henry:9
Lucy:9

到此

Lucy: 4,9
Henry: 8,9

现在已经修好了,谢谢

2 个答案:

答案 0 :(得分:1)

非常直接的解决方案可能是这样的:(如果你不想使用defaultdict)

with open('input.txt') as f:
    dic = {}
    for line in f:
        key,value = line.strip().split(':')
        dic.setdefault(key,[]).append(value)

with open('output','a') as f:
    for key,value in dic.items():
        f.write(key + ':' + ','.join(value) + '\n')

<强> 更新

我修复了你的代码,你需要改变这一行:

  1. 删除以下行,它们在这里没用。

    file = open(class_number, 'a') #opens the file in 'append' mode so you don't delete all the information
    file.write(str(name + ",")) #writes the name and ":" to file
    file.write(str(score)) #writes the score to file
    file.write('\n')#writes the score to the file
    file.close()#safely closes the file to save the information
    
  2. 您使用的是错误的分隔符。

    key,value= line.split(",")
    
  3. 将此更改为:

        key,value= line.strip().split(":")
    

    这将解决您的错误。

    N.B。这里,strip()用于删除空格和换行符。

    1. 别知道,为什么你要咒骂逗号。

      file.write(key + ':' + ',' + ',' + ','.join(value))
      

      将此更改为:

      file.write(key + ':' + ','.join(value) + '\n')
      
    2. 有一件事,你是在读同一个文件。在这种情况下,如果需要写入同一文件,则应立即读取所有内容。但是如果您使用单独的文件,那么您可以使用此代码。

答案 1 :(得分:0)

解决方案1:

最好的方法是首先读取字典中的所有数据,然后将其转储到文件中。

/*

EDIT RECORD

*/
// if the 'id' variable is set in the URL, we know that we need to edit a record
if (isset($_GET['id']))
{
// if the form's submit button is clicked, we need to process the form
if (isset($_POST['submit']))
{
// make sure the 'id' in the URL is valid
if (is_numeric($_POST['id']))
{
// get variables from the URL/form
$id = $_POST['id'];
$addPoints = htmlentities($_POST['addPoints'], ENT_QUOTES);
$remPoints = htmlentities($_POST['remPoints'], ENT_QUOTES);
$reason = htmlentities($_POST['reason'], ENT_QUOTES);
$currPoints = $currPoints+$addPoints-$remPoints;


// if everything is fine, update the record in the database
if ($stmt = $mysqli->prepare("UPDATE points SET currPoints = ? , addPoints = ?, remPoints = ?, reason = ?
WHERE id=?"))
{
$stmt->bind_param("iiisi", $currPoints, $addPoints, $remPoints, $reason, $id);
$stmt->execute();
$stmt->close();
}
// show an error message if the query has an error
else
{
echo "ERROR: could not prepare SQL statement.";
}

// redirect the user once the form is updated
header("Location: index.php");

}
// if the 'id' variable is not valid, show an error message
else
{
echo "Error!";
}
}
// if the form hasn't been submitted yet, get the info from the database and show the form
else
{
// make sure the 'id' value is valid
if (is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// get 'id' from URL
$id = $_GET['id'];

// get the record from the database
if($stmt = $mysqli->prepare("SELECT * FROM points WHERE id=?"))
{
$stmt->bind_param("i", $id);
$stmt->execute();

$stmt->bind_result($id, $name, $currPoints, $addPoints, $remPoints, $reason, $date);
$stmt->fetch();

// show the form
renderForm($name, $currPoints, $addPoints, $remPoints, $reason, NULL, $id);

$stmt->close();
}
// show an error if the query has an error
else
{
echo "Error: could not prepare SQL statement";
}
}
// if the 'id' value is not valid, redirect the user back to the view.php page
else
{
header("Location: index.php");
}
}
}


?>

解决方案2:

对于每个请求,你必须真正整个文件,然后重写它。:

from collections import defaultdict

result = defaultdict(list)

def add_item(classname,source):    
    for name,score in source:
        result[name].append(score)
    with open(classname,'w') as c:
        for key,val in result.items():
            c.write('{}: {}'.format(key,','.join(val))