Skip to content

Commit 8009746

Browse files
committed
Make os.linesep default line_terminator in to_clipboard
Add line_terminator kw to Series.to_csv Refactor to_clipboard Observed problems in to_clipboard: * try..except: pass * excel=None, though it defaults to True * several code paths with return * sep argument could be passed via kwargs * "other keywords are passed to to_csv" only if excel=True * line_terminator kw isn't supported by Series to_csv (+1 squashed commits) Squashed commits: [813f1fc] Make os.linesep default line_terminator in to_clipboard Add line_terminator kw to Series.to_csv Refactor to_clipboard Observed problems in to_clipboard: * try..except: pass * excel=None, though it defaults to True * several code paths with return * sep argument could be passed via kwargs * "other keywords are passed to to_csv" only if excel=True * line_terminator kw isn't supported by Series to_csv
1 parent 37f95ce commit 8009746

File tree

4 files changed

+40
-28
lines changed

4 files changed

+40
-28
lines changed

pandas/core/generic.py

+5-6
Original file line numberDiff line numberDiff line change
@@ -1211,20 +1211,19 @@ def to_pickle(self, path):
12111211
from pandas.io.pickle import to_pickle
12121212
return to_pickle(self, path)
12131213

1214-
def to_clipboard(self, excel=None, sep=None, **kwargs):
1214+
def to_clipboard(self, excel=True, **kwargs):
12151215
"""
12161216
Attempt to write text representation of object to the system clipboard
12171217
This can be pasted into Excel, for example.
12181218
12191219
Parameters
12201220
----------
12211221
excel : boolean, defaults to True
1222-
if True, use the provided separator, writing in a csv
1223-
format for allowing easy pasting into excel.
1222+
if True, use '\\t' separator and os.linesep line terminator by
1223+
default, write to csv format to allow easy pasting into excel.
12241224
if False, write a string representation of the object
12251225
to the clipboard
1226-
sep : optional, defaults to tab
1227-
other keywords are passed to to_csv
1226+
other keywords are passed to to_csv or DataFrame.to_string
12281227
12291228
Notes
12301229
-----
@@ -1234,7 +1233,7 @@ def to_clipboard(self, excel=None, sep=None, **kwargs):
12341233
- OS X: none
12351234
"""
12361235
from pandas.io import clipboard
1237-
clipboard.to_clipboard(self, excel=excel, sep=sep, **kwargs)
1236+
clipboard.to_clipboard(self, excel=excel, **kwargs)
12381237

12391238
def to_xarray(self):
12401239
"""

pandas/core/series.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -2552,7 +2552,8 @@ def from_csv(cls, path, sep=',', parse_dates=True, header=None,
25522552

25532553
def to_csv(self, path=None, index=True, sep=",", na_rep='',
25542554
float_format=None, header=False, index_label=None,
2555-
mode='w', encoding=None, date_format=None, decimal='.'):
2555+
mode='w', encoding=None, date_format=None, decimal='.',
2556+
line_terminator='\n'):
25562557
"""
25572558
Write Series to a comma-separated values (csv) file
25582559
@@ -2584,6 +2585,8 @@ def to_csv(self, path=None, index=True, sep=",", na_rep='',
25842585
decimal: string, default '.'
25852586
Character recognized as decimal separator. E.g. use ',' for
25862587
European data
2588+
line_terminator : string, default '\\n'
2589+
The newline character or character sequence to use in the output file
25872590
"""
25882591
from pandas.core.frame import DataFrame
25892592
df = DataFrame(self)
@@ -2592,7 +2595,7 @@ def to_csv(self, path=None, index=True, sep=",", na_rep='',
25922595
float_format=float_format, header=header,
25932596
index_label=index_label, mode=mode,
25942597
encoding=encoding, date_format=date_format,
2595-
decimal=decimal)
2598+
decimal=decimal, line_terminator=line_terminator)
25962599
if path is None:
25972600
return result
25982601

pandas/io/clipboard.py

+20-20
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
""" io on the clipboard """
2-
from pandas import compat, get_option, option_context, DataFrame
2+
from pandas import compat, get_option, option_context, DataFrame, Series
33
from pandas.compat import StringIO
44

55

@@ -51,7 +51,7 @@ def read_clipboard(**kwargs): # pragma: no cover
5151
return read_table(StringIO(text), **kwargs)
5252

5353

54-
def to_clipboard(obj, excel=None, sep=None, **kwargs): # pragma: no cover
54+
def to_clipboard(obj, excel=True, **kwargs): # pragma: no cover
5555
"""
5656
Attempt to write text representation of object to the system clipboard
5757
The clipboard can be then pasted into Excel for example.
@@ -60,12 +60,11 @@ def to_clipboard(obj, excel=None, sep=None, **kwargs): # pragma: no cover
6060
----------
6161
obj : the object to write to the clipboard
6262
excel : boolean, defaults to True
63-
if True, use the provided separator, writing in a csv
64-
format for allowing easy pasting into excel.
63+
if True, use '\\t' separator and os.linesep line terminator by
64+
default, write to csv format to allow easy pasting into excel.
6565
if False, write a string representation of the object
6666
to the clipboard
67-
sep : optional, defaults to tab
68-
other keywords are passed to to_csv
67+
other keywords are passed to to_csv or DataFrame.to_string
6968
7069
Notes
7170
-----
@@ -75,21 +74,22 @@ def to_clipboard(obj, excel=None, sep=None, **kwargs): # pragma: no cover
7574
- OS X:
7675
"""
7776
from pandas.util.clipboard import clipboard_set
78-
if excel is None:
79-
excel = True
8077

81-
if excel:
82-
try:
83-
if sep is None:
84-
sep = '\t'
85-
buf = StringIO()
86-
obj.to_csv(buf, sep=sep, **kwargs)
87-
clipboard_set(buf.getvalue())
88-
return
89-
except:
90-
pass
91-
92-
if isinstance(obj, DataFrame):
78+
# COMPAT: allow None for `excel` and `sep`
79+
if excel in (True, None) and isinstance(obj, (DataFrame, Series)):
80+
if 'sep' not in kwargs or not kwargs['sep']:
81+
kwargs['sep'] = '\t'
82+
if 'line_terminator' not in kwargs:
83+
import os
84+
kwargs['line_terminator'] = os.linesep
85+
buf = StringIO()
86+
obj.to_csv(buf, **kwargs)
87+
objstr = buf.getvalue()
88+
elif isinstance(obj, DataFrame):
89+
if 'sep' in kwargs:
90+
if kwargs['sep']:
91+
raise ValueError("sep kw is unsupported with excel=False")
92+
del kwargs['sep'] # sep is \t
9393
# str(df) has various unhelpful defaults, like truncation
9494
with option_context('display.max_colwidth', 999999):
9595
objstr = obj.to_string(**kwargs)

pandas/io/tests/test_clipboard.py

+10
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
# -*- coding: utf-8 -*-
2+
import os
3+
24
import numpy as np
35
from numpy.random import randint
46

@@ -80,6 +82,14 @@ def test_round_trip_frame(self):
8082
for dt in self.data_types:
8183
self.check_round_trip_frame(dt)
8284

85+
def test_linesep(self):
86+
pd.DataFrame().to_clipboard()
87+
ret = pandas.util.clipboard.clipboard_get()
88+
assert ret == '""'+os.linesep, "Wrong line separator"
89+
pd.Series([0]).to_clipboard(line_terminator="\t")
90+
ret = pandas.util.clipboard.clipboard_get()
91+
assert ret == "0\t0\t", "Wrong line separator"
92+
8393
def test_read_clipboard_infer_excel(self):
8494
from textwrap import dedent
8595
from pandas.util.clipboard import clipboard_set

0 commit comments

Comments
 (0)