Skip to content

Commit e3cecb5

Browse files
committed
Adding week 05 - file management
1 parent ceae3a9 commit e3cecb5

File tree

8 files changed

+44822
-109
lines changed

8 files changed

+44822
-109
lines changed

Cheatsheets/file_management.py

Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
### FILES & STRUCTURES
2+
# What's in here:
3+
# 1. Files
4+
# 2. Functions
5+
# 3. Exceptions
6+
7+
# - - - - - - - - - - 1. FILES - - - - - - - - - - #
8+
# abrir
9+
fp1 = open('../bar.txt', 'wt') # 'w' de write, 't' de text
10+
fp2 = open('foo.txt', 'rt') # 'r' de read, 't' de text
11+
12+
#escribir
13+
fp1.write('Un texto')
14+
15+
#leer
16+
data = fp2.read()
17+
18+
#cerrar
19+
fp1.close()
20+
fp2.close()
21+
22+
#leer con comando with (cierre automático)
23+
# 1. archivo entero
24+
with open ('foo.txt', 'rt') as file:
25+
data = file.read()
26+
# `data` es una cadena con todo el texto en `foo.txt`
27+
28+
# 2. linea por linea
29+
with open('foo.txt', 'rt') as file:
30+
for line in file:
31+
print(line)
32+
33+
# escribir con comando with (cierre automático)
34+
# 1. "x" - Create - will create a file, returns an error if the file exist
35+
# 2. "a" - Append - will create a file if the specified file does not exist
36+
# 3. "w" - Write - will create a file if the specified file does not exist
37+
lines = ['Readme', 'How to write text files in Python']
38+
with open('readme.txt', 'w') as f:
39+
for line in lines:
40+
f.write(line) # writes a string to a text file.
41+
f.write('\n')
42+
43+
# writeLines()
44+
with open('readme.txt', 'w') as f:
45+
f.writelines(lines) # writes a list of strings to a file at once
46+
47+
# append
48+
with open('readme.txt', 'a') as f:
49+
f.write('\n'.join(lines))
50+
51+
# csv = "Comma-Separated Values"
52+
# El formato CSV es muy común en la importación y exportación de datos en aplicaciones de hojas de cálculo y bases de datos.
53+
import csv
54+
with open('incendios-cantidad-causas-parques-nacionales_2022.csv') as f:
55+
filas = csv.reader(f) # interpreta cada línea como una lista de valores
56+
encabezados = next(filas)
57+
lineas = []
58+
for fila in filas:
59+
lineas.append(fila)
60+
61+
print(encabezados) # ['incendio_anio', 'incendio_total_numero', 'incendio_negligencia_numero', 'incendio_intencional_numero', 'incendio_natural_numero', 'incendio_desconocida_numero']
62+
print(lineas[20]) # ['2013', '21', '7', '9', '0', '5']
63+
64+
# escribir con comando with (cierre automático)
65+
# cadenas
66+
with open('outfile', 'wt') as out:
67+
out.write('Hello World\n')
68+
69+
# ver cwd = "current-working-directory"
70+
import os
71+
print(os.getcwd()) # D:\Diplomatura\Modulo 1\Python basics
72+
print(os.listdir()) # ['.git', '.idea', 'bar.txt', 'Cheatsheets', 'Exercises', 'prueba.py', 'README.md', 'Semanas', 'venv']
73+
74+
# . . . archivo texto
75+
# separado por comas
76+
with open('incendios-cantidad-causas-parques-nacionales_2022.csv', 'rt') as incendios:
77+
lineas = [linea.strip().split(',') for linea in incendios.readlines()]
78+
for linea in lineas:
79+
print(linea) # ['1993', '0', '0', '0', '0', '0']
80+
81+
# separado por espacios
82+
with open('incendios-cantidad-causas-parques-nacionales_2022.txt', 'r') as incendios:
83+
lineas = [linea.strip().split(' ') for linea in incendios.readlines()]
84+
for linea in lineas:
85+
print(linea) # ['1993,0,0,0,0,0']
86+
87+
# . . librerías
88+
# # Panda --> dataframe
89+
# import pandas as pd
90+
# df = pd.read_csv('incendios-cantidad-causas-parques-nacionales_2022.csv')
91+
# print(df)
92+
#
93+
# # Numpy --> matriz
94+
# import numpy as np
95+
# matriz = np.loadtxt('incendios-cantidad-causas-parques-nacionales_2022.csv', delimiter=',')
96+
# print(matriz)
97+
# - - - - - - - - - - 2. FUNCTIONS - - - - - - - - - - #
98+
#funcion clásica
99+
def sumcount(n):
100+
total = 0
101+
while n > 0:
102+
total += n
103+
n -= 1
104+
return total
105+
106+
a = sumcount(100)
107+
print(a)
108+
109+
# funciones de biblioteca
110+
import math
111+
x = math.sqrt(10)
112+
print(round(x, 2))
113+
114+
# break --> saltear actual iteración y pasar a la siguiente
115+
numeros = [1, 2, 3, 4, 5]
116+
for i in numeros:
117+
print(i)
118+
if i == 3:
119+
break
120+
print('bucle finalizado','ultimo valor de i',i)
121+
122+
# continue
123+
numeros = [1, -5, 2, -8, 10]
124+
# imprimo los cuadrados de los números positivos
125+
for i in numeros:
126+
if i <= 0:
127+
continue
128+
print(i**2)
129+
130+
# modules
131+
# Un módulo en Python es un archivo que contiene definiciones de variables, funciones y clases que se pueden utilizar en otros programas.
132+
# Los módulos tienen que ser importados! O sea, debemos decirle a nuestro código que otros archivos queremos utilizar.
133+
# clasico
134+
import math
135+
a = math.pi
136+
v = math.sqrt(9)
137+
138+
# cambio nombre
139+
import math as m
140+
a = m.pi
141+
v = m.sqrt(25)
142+
143+
# solo algunas funciones
144+
from math import sin, cos
145+
r = 2
146+
theta = m.pi
147+
x = r * cos(theta)
148+
149+
150+
# import urllib.request
151+
# u = urllib.request.urlopen('http://www.python.org/')
152+
# data = u.read()
153+
154+
# - - - - - - - - - - 3. EXCEPCIONES - - - - - - - - - - #
155+
# excepción clásica
156+
num_valido = False
157+
while not num_valido:
158+
try:
159+
a = int(input('Ingresa un entero: '))
160+
num_valido = True
161+
except ValueError: # atrapo excepcion y repito ciclo
162+
print('No ingresaste un entero')
163+
print(f'Ingresaste {a}')
164+
165+
# generar excepción
166+
raise RuntimeError('¡Qué cagada!')
167+

Cheatsheets/structures.py

Lines changed: 18 additions & 107 deletions
Original file line numberDiff line numberDiff line change
@@ -1,109 +1,20 @@
1-
### FILES & STRUCTURES
2-
# What's in here:
3-
# 1. Files
4-
# 2. Functions
5-
# 3. Exceptions
6-
# 4. Data Types
7-
# 4.1 Tuple
8-
# 4.2 Dictionary
9-
# 4.3 Container
10-
# 4.4 Sets
11-
# 5. Zip function
12-
# 6. Comprehension
13-
# 7. References and mutability
14-
15-
# - - - - - - - - - - 1. FILES - - - - - - - - - - #
16-
# abrir
17-
fp1 = open('../bar.txt', 'wt') # 'w' de write, 't' de text
18-
fp2 = open('foo.txt', 'rt') # 'r' de read, 't' de text
19-
20-
#escribir
21-
fp1.write('Un texto')
22-
23-
#leer
24-
data = fp2.read()
25-
26-
#cerrar
27-
fp1.close()
28-
fp2.close()
29-
30-
#leer con comando with (cierre automático)
31-
# 1. archivo entero
32-
with open ('foo.txt', 'rt') as file:
33-
data = file.read()
34-
# `data` es una cadena con todo el texto en `foo.txt`
35-
36-
# 2. linea por linea
37-
with open('foo.txt', 'rt') as file:
38-
for line in file:
39-
print(line)
40-
41-
42-
# escribir con comando with (cierre automático)
43-
# cadenas
44-
with open('outfile', 'wt') as out:
45-
out.write('Hello World\n')
46-
47-
48-
# - - - - - - - - - - 2. FUNCTIONS - - - - - - - - - - #
49-
#funcion clásica
50-
def sumcount(n):
51-
total = 0
52-
while n > 0:
53-
total += n
54-
n -= 1
55-
return total
56-
57-
a = sumcount(100)
58-
print(a)
59-
60-
# funciones de biblioteca
61-
import math
62-
x = math.sqrt(10)
63-
print(round(x, 2))
64-
65-
# break --> saltear actual iteración y pasar a la siguiente
66-
numeros = [1, 2, 3, 4, 5]
67-
for i in numeros:
68-
print(i)
69-
if i == 3:
70-
break
71-
print('bucle finalizado','ultimo valor de i',i)
72-
73-
# continue
74-
numeros = [1, -5, 2, -8, 10]
75-
# imprimo los cuadrados de los números positivos
76-
for i in numeros:
77-
if i <= 0:
78-
continue
79-
print(i**2)
80-
81-
# import urllib.request
82-
# u = urllib.request.urlopen('http://www.python.org/')
83-
# data = u.read()
84-
85-
# - - - - - - - - - - 3. EXCEPCIONES - - - - - - - - - - #
86-
# excepción clásica
87-
num_valido = False
88-
while not num_valido:
89-
try:
90-
a = int(input('Ingresa un entero: '))
91-
num_valido = True
92-
except ValueError: # atrapo excepcion y repito ciclo
93-
print('No ingresaste un entero')
94-
print(f'Ingresaste {a}')
95-
96-
# generar excepción
97-
raise RuntimeError('¡Qué cagada!')
98-
99-
100-
# TODO: - - - - - - - - - - 4. TIPOS DE DATOS - - - - - - - - - - #
1+
## STRUCTURES
2+
# 1. Data Types
3+
# 1.1 Tuple
4+
# 1.2 Dictionary
5+
# 1.3 Container
6+
# 1.4 Sets
7+
# 2. Zip function
8+
# 3. Comprehension
9+
# 4. References and mutability
10+
11+
# TODO: - - - - - - - - - - 1. TIPOS DE DATOS - - - - - - - - - - #
10112
# type None
10213
email_address = None
10314
if(email_address):
10415
print('En condicionales, None evalúa como False')
10516

106-
# . . . . . . 4.1 TUPLAS . . . . . . .
17+
# . . . . . . 1.1 TUPLAS . . . . . . .
10718
# para representar registros o estructuras simples (un solo objeto con múltiples partes)
10819
# Contienen una serie de elementos ordenados (indexados), que pueden ser repetidos.
10920
# Son inmutables, no están pensadas para ser modificadas
@@ -166,7 +77,7 @@ def sumcount(n):
16677
dates = list(unzip[1]) #['07/09', '11/11']
16778

16879

169-
# TODO: . . . . . . 4.2 DICCIONARIOS . . . . . . .
80+
# TODO: . . . . . . 1.2 DICCIONARIOS . . . . . . .
17081
# Función que manda claves en valores. Las claves sirven como índices para acceder a los valores.
17182
# Son útiles cuando hay muchos valores diferentes y esos valores pueden ser modificados o manipulados.
17283
# Dado que el acceso a los elementos se hace por clave, no es necesario recordar una posición para cierto dato:
@@ -204,7 +115,7 @@ def sumcount(n):
204115
print(claves) #dict_keys(['nombre', 'cajones', 'precio', 'fecha', 'cuenta'])
205116

206117

207-
# TODO: . . . . . . 4.3 CONTENEDORES . . . . . . .
118+
# TODO: . . . . . . 1.3 CONTENEDORES . . . . . . .
208119
# . . . listas como contenedores
209120
# Usá listas cuando el orden de los datos importe. Acordate de que las listas pueden contener cualquier tipo de objeto.
210121
# Son mutables, pueden ser modificadas sin definir una nueva lista.3
@@ -290,7 +201,7 @@ def sumcount(n):
290201

291202
feriados[(1, 5)] #'Día del trabajador'
292203

293-
# TODO: . . . . . . 4.4 CONJUNTOS . . . . . . .
204+
# TODO: . . . . . . 1.4 CONJUNTOS . . . . . . .
294205
#Un conjunto es una colección de elementos únicos sin orden y sin repetición.
295206
citricos = { 'Naranja','Limon','Mandarina' } #set literal
296207
citricos = set(['Naranja', 'Limon', 'Mandarina']) #set
@@ -315,7 +226,7 @@ def sumcount(n):
315226
s1 - s2 # Diferencia de conjuntos
316227

317228

318-
# TODO: . . . . . . 5. FUNCIÓN ZIP . . . . . . .
229+
# TODO: . . . . . . 2. FUNCIÓN ZIP . . . . . . .
319230
# trabajar sobre dos listas al mismo tiempo
320231
nombres = ['Juan', 'Elsa', 'Ingrid', 'Carlos', 'Federico']
321232
apellidos = ['Pérez', 'Gómez', 'Muller', 'Tacha', 'Higgins']
@@ -348,7 +259,7 @@ def sumcount(n):
348259
print(list(zip(*alumnos))) # [('Carlos Gómez', 'Gabriela Torres', 'Juan Pérez', 'Éric Guay', 'Juana Monte', 'Carla Díaz'), (41008418, 45790918, 48327044, 35360531, 31583398, 43772387), (5, 8, 9, 7, 10, 6)]
349260

350261

351-
# TODO: . . . . . . 6. COMPRENSIÓN LISTAS Y DICCIONARIOS . . . . . . .
262+
# TODO: . . . . . . 3. COMPRENSIÓN LISTAS Y DICCIONARIOS . . . . . . .
352263
# La comprensión de listas crea un una nueva lista aplicando una operación a cada elemento de una secuencia
353264
a = [1, 2, 3, 4, 5]
354265
b = [2*x for x in a] # Creo una lista con el doble de los elementos de a
@@ -389,7 +300,7 @@ def sumcount(n):
389300
suma_pares = sum(n for n in numeros if (n%2)==0)
390301
print(suma_pares) # 24
391302

392-
# TODO: - - - - - - - - 7. REFERENCIAS Y MUTABILIDAD - - - - - - - - - - #
303+
# TODO: - - - - - - - - 4. REFERENCIAS Y MUTABILIDAD - - - - - - - - - - #
393304
# enteros inmutables
394305
a = 10
395306
b = a

0 commit comments

Comments
 (0)