Files
learn-python3/notebooks/beginner/exercises/file_io_exercise.ipynb
2018-05-06 11:33:02 +02:00

113 lines
3.0 KiB
Plaintext

{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"editable": false
},
"outputs": [],
"source": [
"# EXECUTE THIS ONE FIRST!\n",
"\n",
"import os\n",
"\n",
"# Constants for the exercises:\n",
"WORKING_DIR = os.getcwd()\n",
"DATA_DIR = os.path.join(os.path.dirname(WORKING_DIR), 'data')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 1. Sum numbers listed in a file\n",
"Fill ____ pieces of the code below. `sum_numbers_in_file` function takes a input file path as argument, reads the numbers listed in the input file and returns the sum of those numbers. You can assume that each line contains exactly one numeric value."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def sum_numbers_in_file(input_file):\n",
" sum_ = 0 # A common way to use variable names that collide with built-in/keyword words is to add underscore\n",
" with ____(input_file, ____) as ____:\n",
" for line in ____:\n",
" ____ = line.strip() # Remove potential white space \n",
" ____ += float(____)\n",
" return ____"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"editable": false
},
"outputs": [],
"source": [
"in_file = os.path.join(DATA_DIR, 'numbers.txt')\n",
"assert sum_numbers_in_file(in_file) == 189.5"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 2. Reading first word from each line of a file\n",
"Implement `find_first_words` function which takes an input file path as argument. The function should find the first word of each line in the file and return these words as a list. If a line is empty, the returned list should contain an empty string for that line."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Your implementation here"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"editable": false
},
"outputs": [],
"source": [
"in_file1 = os.path.join(DATA_DIR, 'simple_file.txt')\n",
"in_file2 = os.path.join(DATA_DIR, 'simple_file_with_empty_lines.txt')\n",
"\n",
"expected_file_1 = ['First', 'Second', 'Third', 'And']\n",
"assert find_first_words(in_file1) == expected_file_1\n",
"\n",
"expected_file_2 = ['The', '', 'First', 'nonsense', '', 'Then']\n",
"assert find_first_words(in_file2) == expected_file_2"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.5.4"
}
},
"nbformat": 4,
"nbformat_minor": 2
}