如何用逗号分隔一行,但是在引号Python中忽略逗号 [英] How do I split a line by commas, but ignore commas within quotes Python
问题描述
可能重复:
如何读取CSV行?
我看过很多相关问题,但没有直接解决我想要做的事。
我正在从CSV文件中读取文本行。
I have seen a number of related questions but none have directly addressed what I am trying to do. I am reading in lines of text from a CSV file.
所有的项目都在引号中,一些在引号内有一些额外的逗号
我想用逗号分隔行,但忽略引号内的逗号
有办法这在Python中不需要大量的regex语句。
All the items are in quotes and some have additional commas within the quotes. I would like to split the line along commas, but ignore the commas within quotes. Is there a way to do this within Python that does not require a number of regex statements.
例如:
"114111","Planes,Trains,and Automobiles","50","BOOK"
我想解析为4个单独的变量变量:
which I would like parsed into 4 separate variables of values:
"114111" "Planes,Trains,and Automobiles" "50" "Book"
在行中有一个简单的选项
Is there a simple option in line.split()
that I am missing ?
推荐答案
不要尝试重新创造
如果要从CSV文件中读取行,请使用Python的 csv
模块。
If you want to read lines from a CSV file, use Python's csv
module from the standard library.
示例:
> cat test.py
import csv
with open('some.csv') as f:
reader = csv.reader(f)
for row in reader:
print(row)
> cat some.csv
"114111","Planes,Trains,and Automobiles","50","BOOK"
> python test.py
['114111', 'Planes,Trains,and Automobiles', '50', 'BOOK']
[]
工作完成!
这篇关于如何用逗号分隔一行,但是在引号Python中忽略逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!