如何使用python在文件的每一行中检查并插入缺失的变量



我的csv文件看起来像这样:

f1="12345">f2>="abc">f3>="cba"f4="123abc"f5="N">
f1="12345">f2="abc"f4="123abc">f5="Y">
/strong>="abc">f3="cba">f5="Y">1f6="0">

如您所见,缺少一些f变量。

如何使用python使文件看起来像这样?

f1="12345">f2>="abc">f3="cba">>f4="123abc">
f6="NA">
f1>="12345">f2>="abc"f3="NA">="Y">f6="NA">
f1="12345">f2>="abc">f3="cba">f4>="NA">f5>="Y">>f6="0">

我需要所有变量将文件插入mysql-table.

我试过检查是否在行、是否在else和line.find行的功能,但没有成功。

确实找到了使用php:的解决方案

<?php
$input = fopen("startfile.csv", "r");
$output = fopen("endfile.csv", "w");
if ($input) {
while (($line = fgets($input)) !== false) {
// process the line read.
echo $line;
if (strpos($line,'" f5="') !==false) {
//echo "Yes";
} else {
//echo "No";
$line = str_replace('" f6="', '" f5="NA" f6="', $line);
}
if (strpos($line,'" f4="') !==false) {
//echo "Yes";
} else {
//echo "No";
$line = str_replace('" f5="', '" f4="NA" f5="', $line);
}
if (strpos($line,'" f3="') !==false) {
//echo "Yes";
} else {
//echo "No";
$line = str_replace('" f4="', '" f3="NA" f4="', $line);
}
echo $line;
fwrite($output, $line);
}
fclose($input);
} else {
// error opening the file.
}
?>

最新更新