[英]Read in Python with csv.reader a file with two different delimiter in the same file
I want to import a file from MySQL to python but there are two type of delimiters in the same file, on the same line. 我想将文件从MySQL导入python,但是同一文件中同一行上有两种定界符。
For example: 例如:
FIELDA_FIELDB_FIELDC; FILEDD; FIELDE; FIELDF
I can split with _
or ;
我可以用
_
或;
but cant find how to do both. 但找不到如何做到这两者。
I have tried 我努力了
csv_data = csv.reader(csvfile, delimiter=';' and '_')
csv_data = csv.reader(csvfile, delimiter=';' or'_')
I have also tried using csv.sniffer. 我也尝试使用csv.sniffer。
But only one delimiter is used each time. 但是每次仅使用一个定界符。
How should i do ? 我应该怎么做 ?
CSV files can only have one delimiter, so your approach can't work. CSV文件只能有一个定界符,因此您的方法无效。 If you can't fix the broken file, you can read it in two steps (assuming Python 2):
如果无法修复损坏的文件,则可以分两个步骤读取它(假设使用Python 2):
csv_data = []
with open("file.csv", "rb") as csvfile:
reader = csv.reader(csvfile, delimiter=";")
for row in reader:
new = []
for item in row:
new.extend(item.split("_"))
csv_data.append(new)
That solution is of course naive to things like escaped _
delimiters etc., but it might work as intended for you. 该解决方案当然对诸如转义
_
分隔符等天真,但是它可能按预期的方式工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.