Skip to content

Commit e18f154

Browse files
authored
Merge pull request #2722 from pbugnion/avoid-unnecessary-copies-in-file-upload-docs
Avoid unnecessary copies in snippets for file upload
2 parents c54974e + 5ee85e5 commit e18f154

File tree

1 file changed

+14
-5
lines changed

1 file changed

+14
-5
lines changed

docs/source/examples/Widget List.ipynb

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1054,7 +1054,7 @@
10541054
"#=> ]\n",
10551055
"```\n",
10561056
"\n",
1057-
"The contents of the file uploaded are in the value of the `content` key. They are a memory view:\n",
1057+
"The contents of the file uploaded are in the value of the `content` key. They are a [memory view](https://docs.python.org/3/library/stdtypes.html#memory-views):\n",
10581058
"\n",
10591059
"```python\n",
10601060
"[uploaded_file] = uploader.value\n",
@@ -1069,10 +1069,11 @@
10691069
"#=> b'This is the content of example.txt.\\n'\n",
10701070
"```\n",
10711071
"\n",
1072-
"To get the contents as a string:\n",
1072+
"If the file is a text file, you can get the contents as a string by [decoding it](https://docs.python.org/3/library/codecs.html):\n",
10731073
"\n",
10741074
"```python\n",
1075-
"uploaded_file[\"content\"].tobytes().decode(\"utf-8\")\n",
1075+
"import codecs\n",
1076+
"codecs.decode(uploaded_file[\"content\"], encoding=\"utf-8\")\n",
10761077
"#=> 'This is the content of example.txt.\\n'\n",
10771078
"```\n",
10781079
"\n",
@@ -1083,10 +1084,18 @@
10831084
" fp.write(uploaded_file[\"content\"])\n",
10841085
"```\n",
10851086
"\n",
1086-
"To convert the uploaded file into a Pandas dataframe, you need to convert it to a StringIO object:\n",
1087+
"To convert the uploaded file into a Pandas dataframe, you can use a [BytesIO object](https://docs.python.org/3/library/io.html#binary-i-o):\n",
10871088
"\n",
10881089
"```python\n",
1089-
"pd.read_csv(io.StringIO(uploaded_file[\"content\"].tobytes().decode(\"utf-8\")))\n",
1090+
"import io\n",
1091+
"import pandas as pd\n",
1092+
"pd.read_csv(io.BytesIO(uploaded_file[\"content\"]))\n",
1093+
"```\n",
1094+
"\n",
1095+
"If the uploaded file is an image, you can visualize it with an [image](#Image) widget:\n",
1096+
"\n",
1097+
"```python\n",
1098+
"widgets.Image(value=uploaded_file[\"content\"].tobytes())\n",
10901099
"```\n",
10911100
"\n",
10921101
"<div class=\"alert alert-info\">\n",

0 commit comments

Comments
 (0)