简体   繁体   English

Python 3.6+,更改文件中无的表示

[英]Python 3.6+, change representation of None in file

I have to extract from several sources and save the result to csv files.我必须从几个来源中提取并将结果保存到 csv 文件中。 When the data received for a field is None , I want it represented as empty string.当接收到的字段数据为None时,我希望它表示为空字符串。 (I realize I'll lose the distinction between empty string and NULL-type values in the source.) (我意识到我将失去源中空字符串和 NULL 类型值之间的区别。)

My underlying requirement is to preserve the distinction between the string "None" and nothingness in a plain delimited file, without using quotes.我的基本要求是在纯分隔文件中保留字符串“None”和虚无之间的区别,而不使用引号。

I hope to avoid calling a function that checks if a value is null for every nullable field I write, or at least have that call not explicit in the code... eg, I want to just code f.write(row['LastName'] , and if the LastName is "None" get "None", but if it is of NoneType get an empty string.我希望避免调用 function 来检查我编写的每个可空字段的值是否为 null ,或者至少在代码中不明确调用...例如,我只想编写f.write(row['LastName'] ,如果 LastName 为“None”,则为“None”,但如果为NoneType ,则为空字符串。

I haven't yet investigated if the comes-with csv library can do what I need, I will do that, it seems likely that's the easiest approach.我还没有调查附带的 csv 库是否可以满足我的需求,我会这样做,这似乎是最简单的方法。

But: is there anything I can override, so that if I write None to a file, I get empty string (or something besides the string "None" in the output file?但是:有什么我可以覆盖的,所以如果我将None写入文件,我会得到空字符串(或者除了 output 文件中的字符串“None”之外的东西?

It seems to me I'd have to change either 1) the built-in write method of _io.TextIOWrapper or 2) the __str__ method of the NoneType .在我看来,我必须更改 1) _io.TextIOWrapper的内置 write 方法或 2) NoneType__str__方法。

if row['LastName'] is None will check if your value is a NoneType if row['LastName'] is None将检查您的值是否为NoneType

Something like:就像是:

if row['LastName'] is None:
    f.write("")
else:
    f.write(row['LastName'])

Would get the job done.会完成工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM