Python:用QUOTE_NONNUMERIC写CSV,除了None
Python: write CSV with QUOTE_NONNUMERIC, except for None
鉴于数据 ['a', '', None, 5]
我想将 CSV 文件写为:
"a","",,5
如果我使用 QUOTE_NONNUMERIC
,如:
import csv
with open('eggs.csv', 'w') as csvfile:
spamwriter = csv.writer(csvfile, quoting=csv.QUOTE_NONNUMERIC)
spamwriter.writerow(['a', None, 5])
我明白了
"a","","",5
但是如果我删除 quoting=csv.QUOTE_NONNUMERIC
,我会从 Nona
得到未加引号的空字符串,但我也会丢失 a
和空字符串周围的引号。
a,,,5
上下文:我想编写可以使用 R readr r 读取的文件:read_csv('eggs.csv', na=c(""), quoted_na=FALSE)
可以区分空字符串和缺失数据。
使用 处答案(和评论)的变体,您可以将数据中的 None
替换为以下实例:
class EmptyString(int):
def __str__(self):
return ''
然后这将由 Python 的 csv.writer
输出,使用 quoting=csv.QUOTE_NONNUMERIC
作为未加引号的空字符串。更完整的例子:
import csv
class EmptyString(int):
def __str__(self):
return ''
EmptyString = EmptyString()
def replace_none_with_emptystring(row):
return [
val if val is not None else EmptyString
for val in row
]
with open('eggs.csv', 'w') as csvfile:
spamwriter = csv.writer(csvfile, quoting=csv.QUOTE_NONNUMERIC)
spamwriter.writerow(replace_none_with_emptystring(['a', '', None, 5]))
节省
"a","",,5
鉴于数据 ['a', '', None, 5]
我想将 CSV 文件写为:
"a","",,5
如果我使用 QUOTE_NONNUMERIC
,如:
import csv
with open('eggs.csv', 'w') as csvfile:
spamwriter = csv.writer(csvfile, quoting=csv.QUOTE_NONNUMERIC)
spamwriter.writerow(['a', None, 5])
我明白了
"a","","",5
但是如果我删除 quoting=csv.QUOTE_NONNUMERIC
,我会从 Nona
得到未加引号的空字符串,但我也会丢失 a
和空字符串周围的引号。
a,,,5
上下文:我想编写可以使用 R readr r 读取的文件:read_csv('eggs.csv', na=c(""), quoted_na=FALSE)
可以区分空字符串和缺失数据。
使用 处答案(和评论)的变体,您可以将数据中的 None
替换为以下实例:
class EmptyString(int):
def __str__(self):
return ''
然后这将由 Python 的 csv.writer
输出,使用 quoting=csv.QUOTE_NONNUMERIC
作为未加引号的空字符串。更完整的例子:
import csv
class EmptyString(int):
def __str__(self):
return ''
EmptyString = EmptyString()
def replace_none_with_emptystring(row):
return [
val if val is not None else EmptyString
for val in row
]
with open('eggs.csv', 'w') as csvfile:
spamwriter = csv.writer(csvfile, quoting=csv.QUOTE_NONNUMERIC)
spamwriter.writerow(replace_none_with_emptystring(['a', '', None, 5]))
节省
"a","",,5