【发布时间】: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