【问题标题】:How do I check and insert missing variables in each line in file with python?如何使用python检查并在文件的每一行中插入缺失的变量?
【发布时间】:2018-07-19 12:58:49
【问题描述】:

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

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

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

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

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

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

我已经尝试过检查 if not in line 和 if in line else 和 line.find 的功能,但没有运气。

【问题讨论】:

  • 你有什么代码可以给我们看吗?
  • 如果您想获得技术,您提供的示例文件不是 CSV。
  • 不,它不是 csv,它是从 xml 转换而来的。下一步是将 f1、f2、f3 等替换为分号。
  • 这是我的代码:with open(file, 'U') as f: line=f.read() while not '" f3="' in line: line=line.replace(' " f4="', '" f3="NA" f4="') else: line=line.replace('" f3="', '" f3="') 与 open(file, "w") 为f: f.write(line)
  • 等等,csv中每个单元格的内容是“f1=x”的东西吗?或者是你定义的那些变量?

标签: python variables replace text-files missing-data


【解决方案1】:

用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.
}

?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多