Skip to main content
 首页 » 编程设计

python之Pandas:在 CSV 文件中使用整个字符串作为分隔符

2025年05月04日50artech

在我的 CSV 文件中,每一行都用分隔符 "$$$Field$$$" 分隔(简单字符串,不是正则表达式)。我正在尝试执行以下操作,但它忽略了分隔符。

df = pd.read_csv('filename.csv', sep='\b$$$Field$$$\b') 

有什么想法吗?

请您参考如下方法:

看来你需要通过\转义$:

import pandas as pd 
from pandas.compat import StringIO 
 
temp=u"""Food$$$Field$$$Taste 
Apple$$$Field$$$a 
Banana$$$Field$$$b""" 
#after testing replace 'StringIO(temp)' to 'filename.csv' 
df = pd.read_csv(StringIO(temp), sep='\$\$\$Field\$\$\$',engine='python') 
print (df) 
     Food Taste 
0   Apple     a 
1  Banana     b 

read_csv文档:

sep

: str, defaults to ',' for read_csv(), \t for read_table()

Delimiter to use. If sep is None, will try to automatically determine this. Separators longer than 1 character and different from '\s+' will be interpreted as regular expressions, will force use of the python parsing engine and will ignore quotes in the data. Regex example: '\r\t'.