Repository: pandas-dev/pandas

Issue:
Use expanduser when writing dataframes to files?
#### Code Sample, a copy-pastable example if possible

The following `to_XXX` do not work:
```python
df = pd.DataFrame([[1,1],[2,2]])
df.to_pickle('~/df.pkl')
df.to_json('~/df.json')
 # etc.

```
#### Problem description

`to_XXX` do not work when the path argument includes a `~`.  This may be fine, but it is strange that dataframe *reading* from files does support `~`.    i.e. `pd.read_json('~/df.json')` works fine.



#### Expected Output
I expect `to_json` and friends to support expanding the home directory.

Perhaps the fix is to add `expanduser` to https://github.com/pandas-dev/pandas/blob/0d6cb3c21d1305d75878eee7a470bf463b6754bd/pandas/io/common.py#L121
as we have in https://github.com/pandas-dev/pandas/blob/0d6cb3c21d1305d75878eee7a470bf463b6754bd/pandas/io/common.py#L229

#### Output of ``pd.show_versions()``

<details>
INSTALLED VERSIONS
------------------
commit: None
python: 3.6.6.final.0
python-bits: 64
OS: Darwin
OS-release: 17.7.0
machine: x86_64
processor: i386
byteorder: little
LC_ALL: None
LANG: en_US.UTF-8
LOCALE: en_US.UTF-8

pandas: 0.23.4
pytest: 3.9.1
pip: 9.0.1
setuptools: 40.4.1
Cython: 0.27.3
numpy: 1.15.2
scipy: 1.1.0
pyarrow: 0.10.0
xarray: None
IPython: 5.3.0
sphinx: 1.5.1
patsy: 0.4.1
dateutil: 2.7.3
pytz: 2018.5
blosc: None
bottleneck: 1.2.1
tables: 3.4.4
numexpr: 2.6.5
feather: None
matplotlib: 2.2.2
openpyxl: 2.4.1
xlrd: 1.0.0
xlwt: 1.2.0
xlsxwriter: 0.9.6
lxml: 4.1.1
bs4: 4.5.3
html5lib: 0.9999999
sqlalchemy: 1.1.15
pymysql: None
psycopg2: 2.7.1 (dt dec pq3 ext lo64)
jinja2: 2.10
s3fs: 0.1.5
fastparquet: 0.1.3
pandas_gbq: None
pandas_datareader: None

</details>



Discussion:
@gte620v : I think that's a perfectly valid enhancement.  Go for it!
Actually, there is support in `to_html`, `to_csv`, and `to_latex` from https://github.com/pandas-dev/pandas/pull/11458.  I will look at adding to other write functions.

Resolving patch:
diff --git a/pandas/io/common.py b/pandas/io/common.py
--- a/pandas/io/common.py
+++ b/pandas/io/common.py
@@ -157,7 +157,7 @@ def _stringify_path(filepath_or_buffer):
         return text_type(filepath_or_buffer)
     if _PY_PATH_INSTALLED and isinstance(filepath_or_buffer, LocalPath):
         return filepath_or_buffer.strpath
-    return filepath_or_buffer
+    return _expand_user(filepath_or_buffer)
 
 
 def is_s3_url(url):


Test patch:
diff --git a/pandas/tests/io/test_common.py b/pandas/tests/io/test_common.py
--- a/pandas/tests/io/test_common.py
+++ b/pandas/tests/io/test_common.py
@@ -3,6 +3,7 @@
 """
 import mmap
 import os
+import re
 
 import pytest
 
@@ -148,6 +149,31 @@ def test_read_non_existant(self, reader, module, error_class, fn_ext):
         with pytest.raises(error_class):
             reader(path)
 
+    @pytest.mark.parametrize('reader, module, error_class, fn_ext', [
+        (pd.read_csv, 'os', FileNotFoundError, 'csv'),
+        (pd.read_fwf, 'os', FileNotFoundError, 'txt'),
+        (pd.read_excel, 'xlrd', FileNotFoundError, 'xlsx'),
+        (pd.read_feather, 'feather', Exception, 'feather'),
+        (pd.read_hdf, 'tables', FileNotFoundError, 'h5'),
+        (pd.read_stata, 'os', FileNotFoundError, 'dta'),
+        (pd.read_sas, 'os', FileNotFoundError, 'sas7bdat'),
+        (pd.read_json, 'os', ValueError, 'json'),
+        (pd.read_msgpack, 'os', ValueError, 'mp'),
+        (pd.read_pickle, 'os', FileNotFoundError, 'pickle'),
+    ])
+    def test_read_expands_user_home_dir(self, reader, module,
+                                        error_class, fn_ext, monkeypatch):
+        pytest.importorskip(module)
+
+        path = os.path.join('~', 'does_not_exist.' + fn_ext)
+        monkeypatch.setattr(icom, '_expand_user',
+                            lambda x: os.path.join('foo', x))
+
+        message = "".join(["foo", os.path.sep, "does_not_exist.", fn_ext])
+
+        with pytest.raises(error_class, message=re.escape(message)):
+            reader(path)
+
     def test_read_non_existant_read_table(self):
         path = os.path.join(HERE, 'data', 'does_not_exist.' + 'csv')
         with pytest.raises(FileNotFoundError):