{ "cells": [ { "cell_type": "markdown", "metadata": { "hide_input": true, "slideshow": { "slide_type": "slide" } }, "source": [ "# Oinarrizko datu sarrera: `input()`\n", "\n", "* Exekuzio inguruneko sarrera estandarra (teklatua) erabiliko du, erabiltzailearengandik informazioa jasotzeko.\n", "* Exekuzioa geldiarazten du.\n", " * Teklatuaren kasuan,erabiltzaileak *return* tekla sakatu arte\n", "* **`str`** motako objektu bat bueltatzen du" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "slideshow": { "slide_type": "-" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Idatzi zenbaki bat: sdfhsdfhs zfhdf\n", "sdfhsdfhs zfhdf motako objektu bat da\n" ] } ], "source": [ "x = input('Idatzi zenbaki bat: ')\n", "print(f'{x} {type(x)} motako objektu bat da')" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Oinarrizko datu irteera: `print()`\n", "\n", "* Emandako argumentuak karaktere kate bilakatuko dira `str()` funtzioaren bidez, ondoren testu hoiek pantailatik erakusteko." ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on built-in function print in module builtins:\n", "\n", "print(...)\n", " print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n", " \n", " Prints the values to a stream, or to sys.stdout by default.\n", " Optional keyword arguments:\n", " file: a file-like object (stream); defaults to the current sys.stdout.\n", " sep: string inserted between values, default a space.\n", " end: string appended after the last value, default a newline.\n", " flush: whether to forcibly flush the stream.\n", "\n" ] } ], "source": [ "help(print)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ " * `sep` → balioen artean gehitutako karattere katea (defektuz, hutsunea).\n", " * `end` → amaieran gehitutako karaktere katea (defektuz, lerro berri bat).\n", " * `file` → *non* idatzi (defektuz, irteera estandarra).\n", " * `flush` → *flushing*-a behartu ala ez." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Guk *geure* `myprint()` funtzioa sor genezake:" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "kaixo 123 [1, 2, 3] \n", "kaixo 123 [1, 2, 3] \n", "kaixo_|_123_|_[1, 2, 3]_|_#\n", "kaixo_|_123_|_[1, 2, 3]_|_#\n" ] } ], "source": [ "import sys\n", "def myprint(*args, sep=' ', end='\\n', file=sys.stdout):\n", " #print(type(args))\n", " z = []\n", " for x in args :\n", " z.append(str(x))\n", " file.write(sep.join(z) + end)\n", " \n", "print('kaixo',123,[1,2,3],enumerate(\"aeiou\"))\n", "myprint('kaixo',123,[1,2,3],enumerate(\"aeiou\"))\n", "print('kaixo',123,[1,2,3],enumerate(\"aeiou\"),sep='_|_',end='#\\n')\n", "myprint('kaixo',123,[1,2,3],enumerate(\"aeiou\"),sep='_|_',end='#\\n')" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Mintegietan *generadoreak* zer diren ikusiko dugu... Oraingoz, adibide bat:" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "kaixo 123 [1, 2, 3] \n", "kaixo 123 [1, 2, 3] \n", "kaixo_|_123_|_[1, 2, 3]_|_#\n", "kaixo_|_123_|_[1, 2, 3]_|_#\n" ] } ], "source": [ "import sys\n", "def myprint(*args, sep=' ', end='\\n', file=sys.stdout):\n", " file.write(sep.join(str(x) for x in args) + end)\n", " \n", "print('kaixo',123,[1,2,3],enumerate(\"aeiou\"))\n", "myprint('kaixo',123,[1,2,3],enumerate(\"aeiou\"))\n", "print('kaixo',123,[1,2,3],enumerate(\"aeiou\"),sep='_|_',end='#\\n')\n", "myprint('kaixo',123,[1,2,3],enumerate(\"aeiou\"),sep='_|_',end='#\\n')" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Fitxategiak\n", "\n", "* `open()` metodoak *fitxategi* baten abstrakzioa errepresentatzen duen objektua sortzen du.\n", " * Bertatik informazioa irakurri.\n", " * Bertan informazioa idatzi.\n", "* Irikitako fitxategia **itxi** egin behar da beti\n", " * `f=open(...)` → `f.close()`\n", "* Propietateak: Iteragarriak" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on built-in function open in module io:\n", "\n", "open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)\n", " Open file and return a stream. Raise OSError upon failure.\n", " \n", " file is either a text or byte string giving the name (and the path\n", " if the file isn't in the current working directory) of the file to\n", " be opened or an integer file descriptor of the file to be\n", " wrapped. (If a file descriptor is given, it is closed when the\n", " returned I/O object is closed, unless closefd is set to False.)\n", " \n", " mode is an optional string that specifies the mode in which the file\n", " is opened. It defaults to 'r' which means open for reading in text\n", " mode. Other common values are 'w' for writing (truncating the file if\n", " it already exists), 'x' for creating and writing to a new file, and\n", " 'a' for appending (which on some Unix systems, means that all writes\n", " append to the end of the file regardless of the current seek position).\n", " In text mode, if encoding is not specified the encoding used is platform\n", " dependent: locale.getpreferredencoding(False) is called to get the\n", " current locale encoding. (For reading and writing raw bytes use binary\n", " mode and leave encoding unspecified.) The available modes are:\n", " \n", " ========= ===============================================================\n", " Character Meaning\n", " --------- ---------------------------------------------------------------\n", " 'r' open for reading (default)\n", " 'w' open for writing, truncating the file first\n", " 'x' create a new file and open it for writing\n", " 'a' open for writing, appending to the end of the file if it exists\n", " 'b' binary mode\n", " 't' text mode (default)\n", " '+' open a disk file for updating (reading and writing)\n", " 'U' universal newline mode (deprecated)\n", " ========= ===============================================================\n", " \n", " The default mode is 'rt' (open for reading text). For binary random\n", " access, the mode 'w+b' opens and truncates the file to 0 bytes, while\n", " 'r+b' opens the file without truncation. The 'x' mode implies 'w' and\n", " raises an `FileExistsError` if the file already exists.\n", " \n", " Python distinguishes between files opened in binary and text modes,\n", " even when the underlying operating system doesn't. Files opened in\n", " binary mode (appending 'b' to the mode argument) return contents as\n", " bytes objects without any decoding. In text mode (the default, or when\n", " 't' is appended to the mode argument), the contents of the file are\n", " returned as strings, the bytes having been first decoded using a\n", " platform-dependent encoding or using the specified encoding if given.\n", " \n", " 'U' mode is deprecated and will raise an exception in future versions\n", " of Python. It has no effect in Python 3. Use newline to control\n", " universal newlines mode.\n", " \n", " buffering is an optional integer used to set the buffering policy.\n", " Pass 0 to switch buffering off (only allowed in binary mode), 1 to select\n", " line buffering (only usable in text mode), and an integer > 1 to indicate\n", " the size of a fixed-size chunk buffer. When no buffering argument is\n", " given, the default buffering policy works as follows:\n", " \n", " * Binary files are buffered in fixed-size chunks; the size of the buffer\n", " is chosen using a heuristic trying to determine the underlying device's\n", " \"block size\" and falling back on `io.DEFAULT_BUFFER_SIZE`.\n", " On many systems, the buffer will typically be 4096 or 8192 bytes long.\n", " \n", " * \"Interactive\" text files (files for which isatty() returns True)\n", " use line buffering. Other text files use the policy described above\n", " for binary files.\n", " \n", " encoding is the name of the encoding used to decode or encode the\n", " file. This should only be used in text mode. The default encoding is\n", " platform dependent, but any encoding supported by Python can be\n", " passed. See the codecs module for the list of supported encodings.\n", " \n", " errors is an optional string that specifies how encoding errors are to\n", " be handled---this argument should not be used in binary mode. Pass\n", " 'strict' to raise a ValueError exception if there is an encoding error\n", " (the default of None has the same effect), or pass 'ignore' to ignore\n", " errors. (Note that ignoring encoding errors can lead to data loss.)\n", " See the documentation for codecs.register or run 'help(codecs.Codec)'\n", " for a list of the permitted encoding error strings.\n", " \n", " newline controls how universal newlines works (it only applies to text\n", " mode). It can be None, '', '\\n', '\\r', and '\\r\\n'. It works as\n", " follows:\n", " \n", " * On input, if newline is None, universal newlines mode is\n", " enabled. Lines in the input can end in '\\n', '\\r', or '\\r\\n', and\n", " these are translated into '\\n' before being returned to the\n", " caller. If it is '', universal newline mode is enabled, but line\n", " endings are returned to the caller untranslated. If it has any of\n", " the other legal values, input lines are only terminated by the given\n", " string, and the line ending is returned to the caller untranslated.\n", " \n", " * On output, if newline is None, any '\\n' characters written are\n", " translated to the system default line separator, os.linesep. If\n", " newline is '' or '\\n', no translation takes place. If newline is any\n", " of the other legal values, any '\\n' characters written are translated\n", " to the given string.\n", " \n", " If closefd is False, the underlying file descriptor will be kept open\n", " when the file is closed. This does not work when a file name is given\n", " and must be True in that case.\n", " \n", " A custom opener can be used by passing a callable as *opener*. The\n", " underlying file descriptor for the file object is then obtained by\n", " calling *opener* with (*file*, *flags*). *opener* must return an open\n", " file descriptor (passing os.open as *opener* results in functionality\n", " similar to passing None).\n", " \n", " open() returns a file object whose type depends on the mode, and\n", " through which the standard file operations such as reading and writing\n", " are performed. When open() is used to open a file in a text mode ('w',\n", " 'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open\n", " a file in a binary mode, the returned class varies: in read binary\n", " mode, it returns a BufferedReader; in write binary and append binary\n", " modes, it returns a BufferedWriter, and in read/write mode, it returns\n", " a BufferedRandom.\n", " \n", " It is also possible to use a string or bytearray as a file for both\n", " reading and writing. For strings StringIO can be used like a file\n", " opened in a text mode, and for bytes a BytesIO can be used like a file\n", " opened in a binary mode.\n", "\n" ] } ], "source": [ "help(open)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Fitxategiak irekitzeko aukerak - `mode`" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "-" } }, "source": [ "| Character | Meaning |\n", "|:---------:|:-----------------------------------------------------------------|\n", "| `r` | open for reading (default) |\n", "| `w` | open for writing, truncating the file first |\n", "| `x` | open for exclusive creation, failing if the file already exists |\n", "| `a` | open for writing, appending to the end of the file if it exists |\n", "| `b` | binary mode |\n", "| `t` | text mode (default) |\n", "| `+` | open for updating (reading and writing) |" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "f = open(\"MyText.txt\",encoding=\"utf8\")\n", "print(type(f))\n", "f.close()" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "f = open(\"MyText.txt\",\"rt\",encoding=\"utf8\")\n", "print(type(f))\n", "f.close()" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "f = open(\"MyText.txt\",\"rb\")\n", "print(type(f))\n", "f.close()" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## `with` sententzia\n", "\n", "Errekurtsoak (adibidez, fitxategiak) erabiliak diren kasuetan, `with` sententziako _context manager_ -a errekurtsoen kudeaketaz (hasieratu/ireki, amaierazi/itxi) arduratuko da:\n", "\n", "```python\n", "with as x :\n", " # x erabili\n", " ...\n", " ...\n", "# with sententzia amaitzean, x errekurtsoa itxiko da\n", "```" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Fitxategiak euren buruen _context manager_ -ak direnez, with sententziarekin erabil daitezke:" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "with open(\"MyText.txt\",encoding=\"utf8\") as f :\n", " print(type(f))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## (testu) Fitxategiak iteragarriak dira\n", "\n", "* Zeharkatzean _ilarak_ lortzen dira\n", " * `'\\n'`-z amaitutako karaktere kateak \n", " * Azken ilara baliteke ezetz..." ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hau testu fitxategi bat da\n", "Bi ilara ditu\n", "Ez, bi ez, hiru jakiña!\n", "Laugarren bat amaitzeko\n" ] } ], "source": [ "with open(\"MyText.txt\",encoding=\"utf8\") as f :\n", " for x in f :\n", " #print(x,end='')\n", " print(x.rstrip())" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0: Hau testu fitxategi bat da\n", "1: Bi ilara ditu\n", "2: Ez, bi ez, hiru jakiña!\n", "3: Laugarren bat amaitzeko\n" ] } ], "source": [ "with open(\"MyText.txt\",encoding=\"utf8\") as f :\n", " for i,x in enumerate(f) :\n", " print(f'{i}: {x.rstrip()}')" ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['Hau testu fitxategi bat da\\n', 'Bi ilara ditu\\n', 'Ez, bi ez, hiru jakiña!\\n', 'Laugarren bat amaitzeko']\n" ] } ], "source": [ "with open(\"MyText.txt\",encoding=\"utf8\") as f :\n", " print(list(f))" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hau testu fitxategi bat da\n", "Bi ilara ditu\n", "Ez, bi ez, hiru jakiña!\n", "Laugarren bat amaitzeko\n" ] } ], "source": [ "with open(\"MyText.txt\",encoding=\"utf8\") as f :\n", " print(*f,sep='')" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Fitxategiak _agortu_ egiten dira\n", "\n", "* Ezin daitezke bi aldiz zeharkatu\n", "* Beste sekuentzia batzuekin ere gertatzen da" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "---------- 0 ----------\n", "Hau testu fitxategi bat da\n", "Bi ilara ditu\n", "Ez, bi ez, hiru jakiña!\n", "Laugarren bat amaitzeko\n", "---------- 1 ----------\n", "\n", "---------- 2 ----------\n", "\n" ] } ], "source": [ "with open(\"MyText.txt\",encoding=\"utf8\") as f :\n", " for i in range(3):\n", " print('-'*10,i,'-'*10)\n", " print(*f,sep='')" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Zeharkatzeari utzi eta berriro _hastean_ ...\n", "\n", "* Aurreko zeharkatze puntutik aurrera jarraitzen da\n", "* Goiburuak irakurtzeko aproposa. " ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "------------------------------\n", "Hau testu fitxategi bat da\n", "------------------------------\n", "Bi ilara ditu\n", "Ez, bi ez, hiru jakiña!\n", "Laugarren bat amaitzeko\n" ] } ], "source": [ "with open(\"MyText.txt\",encoding=\"utf8\") as f :\n", " for x in f :\n", " print('-'*30)\n", " print(x,end='')\n", " print('-'*30)\n", " break\n", " print(*f,sep='')\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Demagun fitxategi baten lehenengo `n` ilarak goiburua direla:" ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "---------- GOIBURUA ----------\n", "Hau testu fitxategi bat da\n", "Bi ilara ditu\n", "Ez, bi ez, hiru jakiña!\n", "------------------------------\n", "Laugarren bat amaitzeko\n" ] } ], "source": [ "n = 3\n", "with open(\"MyText.txt\",encoding=\"utf8\") as f :\n", " print('-'*10,'GOIBURUA','-'*10)\n", " i = 0\n", " for x in f :\n", " print(x,end='')\n", " i += 1\n", " if i == n :\n", " break\n", " print('-'*30)\n", " print(*f,sep='')\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "**Kontuz** `f` fitxategia beste objektu bati _ematearekin_ zeharkatze _partzial_ bat egiteko.\n", " * Berak ere zeharkatuko badu...\n", " * Ez dakigu **nola** arraio zeharkatzen ote dute" ] }, { "cell_type": "code", "execution_count": 29, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "---------- GOIBURUA ----------\n", "Hau testu fitxategi bat da\n", "Bi ilara ditu\n", "------------------------------\n", "Ez, bi ez, hiru jakiña!\n", "Laugarren bat amaitzeko\n" ] } ], "source": [ "n = 2\n", "with open(\"MyText.txt\",encoding=\"utf8\") as f :\n", " print('-'*10,'GOIBURUA','-'*10)\n", " for i,x in enumerate(f,1) : \n", " print(x,end='')\n", " if i == n :\n", " break\n", " print('-'*30)\n", " print(*f,sep='')\n" ] }, { "cell_type": "code", "execution_count": 30, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "---------- GOIBURUA ----------\n", "Hau testu fitxategi bat da\n", "Bi ilara ditu\n", "------------------------------\n", "Laugarren bat amaitzeko\n" ] } ], "source": [ "n = 2\n", "with open(\"MyText.txt\",encoding=\"utf8\") as f :\n", " print('-'*10,'GOIBURUA','-'*10)\n", " for x,_ in zip(f,range(n)) :\n", " print(x,end='')\n", " print('-'*30)\n", " print(*f,sep='')\n" ] }, { "cell_type": "code", "execution_count": 31, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "---------- GOIBURUA ----------\n", "Hau testu fitxategi bat da\n", "Bi ilara ditu\n", "------------------------------\n", "Ez, bi ez, hiru jakiña!\n", "Laugarren bat amaitzeko\n", "---------- GOIBURUA ----------\n", "Hau testu fitxategi bat da\n", "Bi ilara ditu\n", "------------------------------\n", "Ez, bi ez, hiru jakiña!\n", "Laugarren bat amaitzeko" ] } ], "source": [ "n = 2\n", "with open(\"MyText.txt\",encoding=\"utf8\") as f :\n", " print('-'*10,'GOIBURUA','-'*10)\n", " for _,x in zip(range(n),f) :\n", " print(x,end='')\n", " print('-'*30)\n", " print(*f,sep='')\n", " \n", " \n", "with open(\"MyText.txt\",encoding=\"utf8\") as f :\n", " z = list(f)\n", " print('-'*10,'GOIBURUA','-'*10)\n", " print(*z[:n],sep='',end='')\n", " print('-'*30)\n", " print(*z[n:],sep='',end='')\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Fitxategien berezko metodoak\n", "\n", "* `f.read(size=-1)` → fitxategi osoa irakurri (edo `size` byte)\n", "* `f.readline(size=-1)` → fitxategiaren lerro bat irakurri (edo `size` byte)\n", "* `f.readlines(hint=-1)` → lerro guztiak zerrenda batean bueltatu (gehienez `hint` byte)\n", "* `f.write(text)` → `text` karaktere katea idatzi \n", "* `f.writelines(lines)` → lines karaktere kate segidako elementuak idatzi\n", "* `f.seek(offset, whence=0,)` → fitxategi baten posizio konkretu batean kokatzeko\n", "* `f.close()` → fitxategia itxi" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "**GOGORATU**: `print()` metodoa ere erabil dezakegu `write()` ordez\n", "* `print(...,file=f)`\n", "* Askozaz errazagoa elementu bat baino gehiago idatzi nahi dugunean\n", " * Delimitadorea `sep=...`\n", " * Amaierazlea `end=...`\n", "* Objektuak automatikoki testu bilakatzen dira" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## `repr` eta `eval` \n", "\n", "\n", "* `eval(source, globals=None, locals=None)` → python-eko kodea (karaktere katea) ebaluatu (exekutatu)\n", " * Python-eko kontsola batek behin eta berriro egiten duena (esleipenak salbu)\n", " * Ebaluazioaren emaitza den objektua bueltatzen du\n", "* `repr(obj)` → `obj` objektuaren errepresentazio _kanonikoa_ (karaktere kate gisa) bueltatu\n", " * Objektu bat testu moduan errepresentatzeko modua\n", " * Testu hori ebaluatzean, baliokidea den objektua sortuko da\n", " * `repr(obj)` ≠ `str(obj)`\n", "* `eval(repr(obj)) == obj`" ] }, { "cell_type": "code", "execution_count": 34, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 34, "metadata": {}, "output_type": "execute_result" } ], "source": [ "eval('1+2')" ] }, { "cell_type": "code", "execution_count": 36, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 2, 3]\n" ] } ], "source": [ "z = eval('[1,2,3]')\n", "print(z)" ] }, { "cell_type": "code", "execution_count": 37, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3, 4, 5, 6]" ] }, "execution_count": 37, "metadata": {}, "output_type": "execute_result" } ], "source": [ "eval('z + [4,5,6]')" ] }, { "cell_type": "code", "execution_count": 44, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "'kaixo'" ] }, "execution_count": 44, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#kontuz...\n", "#eval('kaixo')\n", "eval(\"'kaixo'\")\n", "eval('\"kaixo\"')" ] }, { "cell_type": "code", "execution_count": 45, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "['a', 'e', 'i', 'o', 'u']" ] }, "execution_count": 45, "metadata": {}, "output_type": "execute_result" } ], "source": [ "eval(\"['a','e','i','o','u']\")" ] }, { "cell_type": "code", "execution_count": 49, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 2, 3]\n" ] }, { "data": { "text/plain": [ "'kaixo'" ] }, "execution_count": 49, "metadata": {}, "output_type": "execute_result" } ], "source": [ "print(repr([1,2,3]))\n", "repr([1,2,3])" ] }, { "cell_type": "code", "execution_count": 50, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n", "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n", "True False\n" ] } ], "source": [ "z=list(range(10))\n", "print(z)\n", "print(repr(z))\n", "print(eval(repr(z)) == z , eval(repr(z)) is z)" ] }, { "cell_type": "code", "execution_count": 51, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{1: 'kaixo', 2: [1, 2, 3], 3: (5, 6, 7)}\n", "{1: 'kaixo', 2: [1, 2, 3], 3: (5, 6, 7)}\n", "True\n" ] } ], "source": [ "h = {1:\"kaixo\" , 2:[1,2,3] , 3:(5,6,7)}\n", "print(h)\n", "print(repr(h))\n", "print(eval(repr(h)) == h)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Zein da `str()` eta `repr()` arteko ezberdintasuna?" ] }, { "cell_type": "code", "execution_count": 53, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "OK \n", "OK \n", "OK \n", "WARNING: str=kaixo repr='kaixo'\n", "OK \n", "OK \n", "OK \n", "OK \n", "OK \n", "[1, 23, 3, 'kaixo']\n" ] } ], "source": [ "for x in 12, 12.45, True, \"kaixo\", [1,2,3], [1,2,3,\"kaixo\"], (1,2,3), {1:2,3:4}, [1,2,3,(4,5,[6,7,{1:2,3:4}])] :\n", " if str(x)==repr(x) :\n", " print('OK' , type(x))\n", " else :\n", " print(f'WARNING: str={str(x)} repr={repr(x)}',)\n", "\n", "z = [1,23,3,'kaixo']\n", "print(z)" ] }, { "cell_type": "code", "execution_count": 54, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[1, 2, 3], [4, 5, 6]]\n", "[[1, 2, 3], [4, 5, 6]]\n" ] } ], "source": [ "A = [[1,2,3],[4,5,6]]\n", "B = eval(repr(A))\n", "print(A)\n", "print(B)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "`eval(repr(o))` egitean `o` objectuaren _balioa_ mantenduko da, ez bere _egitura_" ] }, { "cell_type": "code", "execution_count": 55, "metadata": { "slideshow": { "slide_type": "-" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[1, 2, 3], [1, 2, 3], [1, 2, 3]]\n", "[[1, 2, 3], [1, 2, 3], [1, 2, 3]]\n", "True\n", "True False\n" ] } ], "source": [ "z = [1,2,3]\n", "zz = [z,z,z]\n", "print(str(zz))\n", "print(repr(zz))\n", "x = eval(repr(zz))\n", "print(zz == x)\n", "print(zz[0] is zz[1], x[0] is x[1])" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "-" } }, "source": [ "Ikusi kodea [Python Tutor-en](https://pythontutor.com/live.html#code=z%20%3D%20%5B23,564,234521%5D%0Azz%20%3D%20%5Bz,z,z%5D%0Ax%20%3D%20eval%28repr%28zz%29%29%0A&cumulative=false&curInstr=6&heapPrimitives=nevernest&mode=display&origin=opt-live.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Objektu bat fitxategi batean gordetzen" ] }, { "cell_type": "code", "execution_count": 56, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "z = [1,200,3,(4,5,[6,7,{1:'bat',3:'hiru'}])]\n", "with open('MyData.txt','wt',encoding='utf8') as f :\n", " f.write(repr(z))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "### Objektu bat fitxategi batetik irakurtzen" ] }, { "cell_type": "code", "execution_count": 57, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 200, 3, (4, 5, [6, 7, {1: 'bat', 3: 'hiru'}])]\n" ] } ], "source": [ "with open('MyData.txt','rt',encoding='utf8') as f :\n", " x = eval(f.read())\n", " print(x)" ] }, { "cell_type": "code", "execution_count": 58, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 200, 3, (4, 5, [6, 7, {1: 'bat', 3: 'hiru'}])]\n", "[1, 200, 3, (4, 5, [6, 7, {1: 'bat', 3: 'hiru'}])]\n", "True False\n" ] } ], "source": [ "print(z)\n", "print(x)\n", "print(z==x,z is x)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Bi funtzio sor ditzakegu... " ] }, { "cell_type": "code", "execution_count": 59, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "def savetxt(obj,filename,encoding='utf8'):\n", " with open(filename,'wt',encoding=encoding) as f :\n", " f.write(repr(obj))\n", " \n", "def loadtxt(filename,encoding='utf8'):\n", " with open(filename,'rt',encoding=encoding) as f :\n", " return eval(f.read())" ] }, { "cell_type": "code", "execution_count": 60, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 60, "metadata": {}, "output_type": "execute_result" } ], "source": [ "z = {1:'bat',2:'bi',3:['???',56,7,\"XXXXXXXXXXXX\"]}\n", "savetxt(z,'MyData.txt')\n", "loadtxt('MyData.txt') == z" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Objektu bat baina gehiago gorde nahi badugu, egitura bakarrean (nkote batetan adibidez) gorde ditzakegu..." ] }, { "cell_type": "code", "execution_count": 61, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 61, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = [1,2,3,(4,5,[6,7,{1:'bat',3:'hiru'}])]\n", "b = {1:'bat',2:'bi',3:['???',56,7]}\n", "savetxt((a,b),'MyData.txt')\n", "x,y = loadtxt('MyData.txt')\n", "a == x and b == y" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## `pickle` modulua \n", "\n", "* Serializazio (objektua → byte segida) bidez objektuak fitxategietan gorde\n", "* Formatu bitarra\n", " * Bizkorra\n", " * Tamaina minimoa\n", " * Irakurtezina\n", "* Oinarrizko bi metodo:\n", " * `pickle.dump(obj, file)` → objektua fitxategian idatzi\n", " * `pickle.load(file)` → fitxategitik objektu bat irakurri\n", " * `file` : modu bitarrean idatzi/irakurri daitekeen fitxategia\n", " * **EZ DA FITXATEGI IZENA**" ] }, { "cell_type": "code", "execution_count": 62, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 62, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import pickle\n", "\n", "a = [1,2,3,(4,5,[6,7,{1:'bat',3:'hiru'}])]\n", "b = {1:'bat',2:'bi',3:['???',56,7]}\n", "\n", "with open('MyData.dat','wb') as f :\n", " pickle.dump(a,f)\n", " pickle.dump(b,f)\n", "\n", "with open('MyData.dat','rb') as f :\n", " x = pickle.load(f)\n", " y = pickle.load(f)\n", "\n", "a == x and b == y" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Berriro ere, bi funtzio sor ditzakegu... " ] }, { "cell_type": "code", "execution_count": 63, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "import pickle\n", "\n", "def savebin(obj,filename):\n", " with open(filename,'wb') as f :\n", " pickle.dump(obj,f)\n", " \n", "def loadbin(filename):\n", " with open(filename,'rb') as f :\n", " return pickle.load(f)" ] }, { "cell_type": "code", "execution_count": 64, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 64, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = [1,2,3,(4,5,[6,7,{1:'bat',3:'hiru'}])]\n", "b = {1:'bat',2:'bi',3:['???',56,7]}\n", "savebin((a,b),'MyData.dat')\n", "x,y = loadbin('MyData.dat')\n", "a == x and b == y" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Kontuz _generadoreekin_ (`enumerate`, `zip`, ...)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "print(repr(enumerate(\"aeiou\")))\n", "#eval(repr(enumerate(\"aeiou\")))\n", "print(repr(zip(\"aeiou\",range(10))))\n", "#eval(repr(zip(\"aeiou\",range(10))))\n", "\n", "a = enumerate(\"aeiou\")\n", "savebin(a,'MyData.dat')\n", "b= loadbin('MyData.dat')\n", "print(*a)\n", "print(*b)\n", "print(a == b , enumerate(\"aeiou\") == enumerate(\"aeiou\"))\n", "\n", "print(enumerate(\"aeiou\") == enumerate(\"aeiou\"))\n", "print(list(enumerate(\"aeiou\")) == list(enumerate(\"aeiou\")))\n", "\n", "print(zip(\"aeiou\",range(10)) == zip(\"aeiou\",range(10)))\n", "print(list(zip(\"aeiou\",range(10))) == list(zip(\"aeiou\",range(10))))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "-" } }, "source": [ "\n", " \n", " \n", " \n", "\n", "
< < Hiztegiak < <> > Random Modulua > >
" ] } ], "metadata": { "celltoolbar": "Slideshow", "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.7.6" }, "rise": { "autolaunch": false, "footer": "

Konputaziorako Sarrera

", "scroll": true } }, "nbformat": 4, "nbformat_minor": 2 }