csv 按逗号分割,如果逗号引用了元组列表中的数据,则忽略该数据- Python

zynd9foi  于 2023-10-13  发布在  Python
关注(0)|答案(3)|浏览(94)

我有一个元组列表。

lt = [('051623', 'O143', '1.23', '2023-05-16T18:30:00', '1M allen', 'millan'), ('051623', 'O207', '1.23', '2023-05-16T18:35:00', 'nM Mn, 4nM, 35uM Fe', 'wilo')]

需要转换为CSV字符串由逗号分隔,但同时分割引号内的逗号被忽略:预计在下面。

'051623','O143','1.23','2023-05-16T18:30:00','1M allen','millan'
'051623', 'O207', '1.23', '2023-05-16T18:35:00','nM Mn, 4nM, 35uM Fe','wilo'

我试过,但没有工作:

csv_string = '\n'.join(",".join([element if element else 'None' for element in tup]) for tup in lt)
k75qkfdt

k75qkfdt1#

您可以使用csv库:

lt = [
  ('051623', 'O143', '1.23', '2023-05-16T18:30:00', '1M allen', 'millan'), 
  ('051623', 'O207', '1.23', '2023-05-16T18:35:00', 'nM Mn, 4nM, 35uM Fe', 'wilo'),
]

import io
import csv

# Allows saving the csv output to a string instead of a file
f = io.StringIO(newline='')    

writer = csv.writer(
    f,
    quotechar="'",
    quoting=csv.QUOTE_ALL,
)
writer.writerows(lt)

# `getvalue()` returns a string containing the csv output
print(f.getvalue())

它输出

'051623','O143','1.23','2023-05-16T18:30:00','1M allen','millan'
'051623','O207','1.23','2023-05-16T18:35:00','nM Mn, 4nM, 35uM Fe','wilo'
t0ybt7op

t0ybt7op2#

这里有一个例子。

s = '\n'.join([','.join([f"'{y}'" for y in x]) for x in lt])

输出

'051623','O143','1.23','2023-05-16T18:30:00','1M allen','millan'
'051623','O207','1.23','2023-05-16T18:35:00','nM Mn, 4nM, 35uM Fe','wilo'

此外,您还需要转义文本中的任何单引号。

s = '\n'.join([','.join([f"'{y}'" for y in [z.replace("'", r"\'") for z in x]]) for x in lt])
kq0g1dla

kq0g1dla3#

如果您只是尝试将行重新组合为CSV数据,而不是实际写入CSV,则可以使用以下方法,它将每个值都用双引号括起来

lines=[]
for tup in lt:
    lines.append('"' + '","'.join(tup)+'"')

print(lines)
# [
# '"051623","O143","1.23","2023-05-16T18:30:00","1M allen","millan"',
# '"051623","O207","1.23","2023-05-16T18:35:00","nM Mn, 4nM, 35uM Fe","wilo"'
# ]

或者,如果您只想换行包含逗号的单元格:

lines=[]
for tup in lt:
    line=''
    for el in tup:
        if ',' in el:
            el = '"'+el+'"'
        line += el + ','
    lines.append(line[:-1]) # Strip the extra , at the end

print(lines)
# [
#   '051623,O143,1.23,2023-05-16T18:30:00,1M allen,millan',
#   '051623,O207,1.23,2023-05-16T18:35:00,"nM Mn, 4nM, 35uM Fe",wilo'
# ]

相关问题