Solving error "delimiter must be a 1-character string" while writing a dataframe to a csv file
delimiter, pandas
Solution
As mentioned in the issue discussion (here), this is not considered as a pandas issue but rather a compatibility issue of `python's csv module` with python2.x.
The workaround to solve it is to enclose the separator with `str(..)`. For example, here is how you can reproduce the problem, and then solve it:
from __future__ import unicode_literals
import pandas as pd
df = pd.DataFrame([['a', 'A'], ['b', 'B']])
df.to_csv(sep=',')
This will raise the following error:
TypeError ....
----> 1 df.to_csv(sep=',')
TypeError: "delimiter" must be an 1-character string
The following however, will show the expected result
from __future__ import unicode_literals
import pandas as pd
df = pd.DataFrame([['a', 'A'], ['b', 'B']])
df.to_csv(sep=str(','))
Output:
',0,1\n0,a,A\n1,b,B\n'
In your case, you should edit your code as follows:
df.to_csv('/Users/Lab/Desktop/filteredwithheading.txt', sep=str('\s+'), header=True)
Problem
Using this question: Pandas writing dataframe to CSV file as a model, I wrote the following code to make a csv file: ``` df.to_csv('/Users/Lab/Desktop/filteredwithheading.txt', sep='\s+', header=True) ``` But it returns the following error: ``` TypeError: "delimiter" must be an 1-character string ``` I have looked up the documentation for this here http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html but I can't figure out what I am missing, or what that error means. I also tried using (sep='\s') in the code, but got the same error.