|
1054 | 1054 | "#=> ]\n",
|
1055 | 1055 | "```\n",
|
1056 | 1056 | "\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", |
1058 | 1058 | "\n",
|
1059 | 1059 | "```python\n",
|
1060 | 1060 | "[uploaded_file] = uploader.value\n",
|
|
1069 | 1069 | "#=> b'This is the content of example.txt.\\n'\n",
|
1070 | 1070 | "```\n",
|
1071 | 1071 | "\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", |
1073 | 1073 | "\n",
|
1074 | 1074 | "```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", |
1076 | 1077 | "#=> 'This is the content of example.txt.\\n'\n",
|
1077 | 1078 | "```\n",
|
1078 | 1079 | "\n",
|
|
1083 | 1084 | " fp.write(uploaded_file[\"content\"])\n",
|
1084 | 1085 | "```\n",
|
1085 | 1086 | "\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", |
1087 | 1088 | "\n",
|
1088 | 1089 | "```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", |
1090 | 1099 | "```\n",
|
1091 | 1100 | "\n",
|
1092 | 1101 | "<div class=\"alert alert-info\">\n",
|
|
0 commit comments