Manejo de archivos externos¶
Python tiene una función built-in llamada open que nos permite abrir archivo como .txt, .csv, .xlsx, ...
Sin embargo, es cierto, que según el tipo de archivo, python tiene módulos específicos para manejar más cómodamente cada archivo.
Ejemplos:
- csv para archivos csv (Comma separated values)
- json para archivos json (JavaScript object notation)
Daremos algunos ejemplos para que todo se entienda mejor.
Acceso a la documentación¶
In [1]:
Copied!
help(open)
help(open)
Help on function open in module io:
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Open file and return a stream. Raise OSError upon failure.
file is either a text or byte string giving the name (and the path
if the file isn't in the current working directory) of the file to
be opened or an integer file descriptor of the file to be
wrapped. (If a file descriptor is given, it is closed when the
returned I/O object is closed, unless closefd is set to False.)
mode is an optional string that specifies the mode in which the file
is opened. It defaults to 'r' which means open for reading in text
mode. Other common values are 'w' for writing (truncating the file if
it already exists), 'x' for creating and writing to a new file, and
'a' for appending (which on some Unix systems, means that all writes
append to the end of the file regardless of the current seek position).
In text mode, if encoding is not specified the encoding used is platform
dependent: locale.getpreferredencoding(False) is called to get the
current locale encoding. (For reading and writing raw bytes use binary
mode and leave encoding unspecified.) The available modes are:
========= ===============================================================
Character Meaning
--------- ---------------------------------------------------------------
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' create a new file and open it for writing
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newline mode (deprecated)
========= ===============================================================
The default mode is 'rt' (open for reading text). For binary random
access, the mode 'w+b' opens and truncates the file to 0 bytes, while
'r+b' opens the file without truncation. The 'x' mode implies 'w' and
raises an `FileExistsError` if the file already exists.
Python distinguishes between files opened in binary and text modes,
even when the underlying operating system doesn't. Files opened in
binary mode (appending 'b' to the mode argument) return contents as
bytes objects without any decoding. In text mode (the default, or when
't' is appended to the mode argument), the contents of the file are
returned as strings, the bytes having been first decoded using a
platform-dependent encoding or using the specified encoding if given.
'U' mode is deprecated and will raise an exception in future versions
of Python. It has no effect in Python 3. Use newline to control
universal newlines mode.
buffering is an optional integer used to set the buffering policy.
Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
line buffering (only usable in text mode), and an integer > 1 to indicate
the size of a fixed-size chunk buffer. When no buffering argument is
given, the default buffering policy works as follows:
* Binary files are buffered in fixed-size chunks; the size of the buffer
is chosen using a heuristic trying to determine the underlying device's
"block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
On many systems, the buffer will typically be 4096 or 8192 bytes long.
* "Interactive" text files (files for which isatty() returns True)
use line buffering. Other text files use the policy described above
for binary files.
encoding is the name of the encoding used to decode or encode the
file. This should only be used in text mode. The default encoding is
platform dependent, but any encoding supported by Python can be
passed. See the codecs module for the list of supported encodings.
errors is an optional string that specifies how encoding errors are to
be handled---this argument should not be used in binary mode. Pass
'strict' to raise a ValueError exception if there is an encoding error
(the default of None has the same effect), or pass 'ignore' to ignore
errors. (Note that ignoring encoding errors can lead to data loss.)
See the documentation for codecs.register or run 'help(codecs.Codec)'
for a list of the permitted encoding error strings.
newline controls how universal newlines works (it only applies to text
mode). It can be None, '', '\n', '\r', and '\r\n'. It works as
follows:
* On input, if newline is None, universal newlines mode is
enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
these are translated into '\n' before being returned to the
caller. If it is '', universal newline mode is enabled, but line
endings are returned to the caller untranslated. If it has any of
the other legal values, input lines are only terminated by the given
string, and the line ending is returned to the caller untranslated.
* On output, if newline is None, any '\n' characters written are
translated to the system default line separator, os.linesep. If
newline is '' or '\n', no translation takes place. If newline is any
of the other legal values, any '\n' characters written are translated
to the given string.
If closefd is False, the underlying file descriptor will be kept open
when the file is closed. This does not work when a file name is given
and must be True in that case.
A custom opener can be used by passing a callable as *opener*. The
underlying file descriptor for the file object is then obtained by
calling *opener* with (*file*, *flags*). *opener* must return an open
file descriptor (passing os.open as *opener* results in functionality
similar to passing None).
open() returns a file object whose type depends on the mode, and
through which the standard file operations such as reading and writing
are performed. When open() is used to open a file in a text mode ('w',
'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
a file in a binary mode, the returned class varies: in read binary
mode, it returns a BufferedReader; in write binary and append binary
modes, it returns a BufferedWriter, and in read/write mode, it returns
a BufferedRandom.
It is also possible to use a string or bytearray as a file for both
reading and writing. For strings StringIO can be used like a file
opened in a text mode, and for bytes a BytesIO can be used like a file
opened in a binary mode.
Lectura/Escritura clásica¶
Lectura¶
In [2]:
Copied!
filename = r'C:\Users\sergi\Documents\repos\python_course\data\Dummy.txt' # Es buena idea usar r delante de los paths explícitos cuando estamos en Windows.
txt_file = open(filename, mode = 'r')
content = txt_file.read()
txt_file = open(filename, mode = 'r')
content_first_line = txt_file.readline()
txt_file = open(filename, mode = 'r')
content_first_second_lines = txt_file.readlines(19) # Leemos hasta dónde se supera el nº de caracteres | hint=-1 lee todo
txt_file.close() # Cuando no se usa se cierra explícitamente
print(f'{content=} \n{content_first_line=} \n{content_first_second_lines=}')
filename = r'C:\Users\sergi\Documents\repos\python_course\data\Dummy.txt' # Es buena idea usar r delante de los paths explícitos cuando estamos en Windows.
txt_file = open(filename, mode = 'r')
content = txt_file.read()
txt_file = open(filename, mode = 'r')
content_first_line = txt_file.readline()
txt_file = open(filename, mode = 'r')
content_first_second_lines = txt_file.readlines(19) # Leemos hasta dónde se supera el nº de caracteres | hint=-1 lee todo
txt_file.close() # Cuando no se usa se cierra explícitamente
print(f'{content=} \n{content_first_line=} \n{content_first_second_lines=}')
content='AAAAAAAAAAAAAAAAAA\nBBBBBBBBBBBBBBBBBB\nCCCCCCCCCCCCCCCCCC\nDDDDDDDDDDDDDDDDDD\n' content_first_line='AAAAAAAAAAAAAAAAAA\n' content_first_second_lines=['AAAAAAAAAAAAAAAAAA\n', 'BBBBBBBBBBBBBBBBBB\n']
Lectura y Escritura¶
In [3]:
Copied!
filename = r'C:\Users\sergi\Documents\repos\python_course\data\Dummy.txt' # Es buena idea usar r delante de los paths explícitos cuando estamos en Windows.
txt_file = open(filename, mode = 'r+') # Leer y escribir
txt_file.write(txt_file.read() + '\n')
txt_file.write('E' * 18 + '\n')
txt_file.close()
filename = r'C:\Users\sergi\Documents\repos\python_course\data\Dummy.txt' # Es buena idea usar r delante de los paths explícitos cuando estamos en Windows.
txt_file = open(filename, mode = 'r+') # Leer y escribir
txt_file.write(txt_file.read() + '\n')
txt_file.write('E' * 18 + '\n')
txt_file.close()
Append (Si ya existe, escribe al final)¶
In [4]:
Copied!
filename = r'C:\Users\sergi\Documents\repos\python_course\data\Dummy.txt' # Es buena idea usar r delante de los paths explícitos cuando estamos en Windows.
txt_file = open(filename, mode = 'a')
txt_file.write('F' * 18 + '\n')
txt_file.close()
filename = r'C:\Users\sergi\Documents\repos\python_course\data\Dummy.txt' # Es buena idea usar r delante de los paths explícitos cuando estamos en Windows.
txt_file = open(filename, mode = 'a')
txt_file.write('F' * 18 + '\n')
txt_file.close()
Estructura with open¶
In [5]:
Copied!
filename = r'C:\Users\sergi\Documents\repos\python_course\data\Dummy.txt' # Es buena idea usar r delante de los paths explícitos cuando estamos en Windows.
with open(filename, 'r') as txt_file:
content = txt_file.read()
print(content)
filename = r'C:\Users\sergi\Documents\repos\python_course\data\Dummy.txt' # Es buena idea usar r delante de los paths explícitos cuando estamos en Windows.
with open(filename, 'r') as txt_file:
content = txt_file.read()
print(content)
AAAAAAAAAAAAAAAAAA BBBBBBBBBBBBBBBBBB CCCCCCCCCCCCCCCCCC DDDDDDDDDDDDDDDDDD AAAAAAAAAAAAAAAAAA BBBBBBBBBBBBBBBBBB CCCCCCCCCCCCCCCCCC DDDDDDDDDDDDDDDDDD EEEEEEEEEEEEEEEEEE FFFFFFFFFFFFFFFFFF
Manejo con módulos específicos¶
CSV¶
In [8]:
Copied!
import csv
csv_path = r'C:\Users\sergi\Documents\repos\python_course\data\data.csv'
## READ
with open(csv_path) as csv_file:
reader = csv.DictReader(csv_file, delimiter = ',')
for row in reader:
print(row)
## WRITE
with open(csv_path, 'a') as csv_file:
spamwriter = csv.DictWriter(csv_file, delimiter = ',', fieldnames = list(row.keys()))
spamwriter.writerow(row)
import csv
csv_path = r'C:\Users\sergi\Documents\repos\python_course\data\data.csv'
## READ
with open(csv_path) as csv_file:
reader = csv.DictReader(csv_file, delimiter = ',')
for row in reader:
print(row)
## WRITE
with open(csv_path, 'a') as csv_file:
spamwriter = csv.DictWriter(csv_file, delimiter = ',', fieldnames = list(row.keys()))
spamwriter.writerow(row)
{'UUID': '65.tif', 'LONG': '36.47207866666667', 'LAT': '-6.249120222222222'}
{'UUID': '65.tif', 'LONG': '36.47207866666667', 'LAT': '-6.249120222222222'}
{'UUID': '65.tif', 'LONG': '36.47207866666667', 'LAT': '-6.249120222222222'}
{'UUID': '65.tif', 'LONG': '36.47207866666667', 'LAT': '-6.249120222222222'}
{'UUID': '65.tif', 'LONG': '36.47207866666667', 'LAT': '-6.249120222222222'}
{'UUID': '65.tif', 'LONG': '36.47207866666667', 'LAT': '-6.249120222222222'}
JSON¶
In [7]:
Copied!
import json
json_path = r'C:\Users\sergi\Documents\repos\python_course\data\config.json'
## READ
with open(json_path) as json_file:
data = json.load(json_file)
print(data)
## WRITE
with open(json_path, 'w') as json_file:
data['WRITE'] = None
data = json.dump(data, json_file)
import json
json_path = r'C:\Users\sergi\Documents\repos\python_course\data\config.json'
## READ
with open(json_path) as json_file:
data = json.load(json_file)
print(data)
## WRITE
with open(json_path, 'w') as json_file:
data['WRITE'] = None
data = json.dump(data, json_file)
{'ok': True, 'fail': False}
YAML¶
In [8]:
Copied!
import yaml
yaml_path = r'C:\Users\sergi\Documents\repos\python_course\data\config.yml'
## READ
with open(yaml_path, "r") as yml_file:
try:
data = yaml.safe_load(yml_file)
print(data)
except yaml.YAMLError as exc:
print(exc)
## WRITE
with open(yaml_path, "a") as yml_file:
try:
data['WRITE'] = None
yaml.dump(data, yml_file)
except yaml.YAMLError as exc:
print(exc)
import yaml
yaml_path = r'C:\Users\sergi\Documents\repos\python_course\data\config.yml'
## READ
with open(yaml_path, "r") as yml_file:
try:
data = yaml.safe_load(yml_file)
print(data)
except yaml.YAMLError as exc:
print(exc)
## WRITE
with open(yaml_path, "a") as yml_file:
try:
data['WRITE'] = None
yaml.dump(data, yml_file)
except yaml.YAMLError as exc:
print(exc)
{'n_processed': 1, 'logs': {0: 'OK', 1: 'OK', 2: 'OK', 3: 'KO', 4: 'OK', 5: 'OK', 6: 'KO', 7: 'OK', 8: 'KO', 9: 'OK'}}
TIF¶
In [9]:
Copied!
import rasterio
from pprint import pprint
tif_path = r'C:\Users\sergi\Documents\repos\python_course\data\rgb.tif'
## READ
with rasterio.open(tif_path, 'r') as src:
data = src.read()
profile = src.profile
pprint(f'{profile=}')
print(f'{data.shape=}')
## WRITE
with rasterio.open(tif_path, 'w', **profile) as dst:
dst.write(data)
import rasterio
from pprint import pprint
tif_path = r'C:\Users\sergi\Documents\repos\python_course\data\rgb.tif'
## READ
with rasterio.open(tif_path, 'r') as src:
data = src.read()
profile = src.profile
pprint(f'{profile=}')
print(f'{data.shape=}')
## WRITE
with rasterio.open(tif_path, 'w', **profile) as dst:
dst.write(data)
("profile={'driver': 'GTiff', 'dtype': 'uint8', 'nodata': None, 'width': 433, "
"'height': 578, 'count': 4, 'crs': None, 'transform': Affine(1.0, 0.0, 0.0,\n"
" 0.0, 1.0, 0.0), 'blockysize': 7, 'tiled': False, 'compress': 'lzw', "
"'interleave': 'pixel'}")
data.shape=(4, 578, 433)
c:\Users\sergi\Documents\repos\python_course\course-venv\lib\site-packages\rasterio\__init__.py:330: NotGeoreferencedWarning: The given matrix is equal to Affine.identity or its flipped counterpart. GDAL may ignore this matrix and save no geotransform without raising an error. This behavior is somewhat driver-specific. dataset = writer(
Excel¶
In [10]:
Copied!
import openpyxl
workbook = openpyxl.load_workbook(filename = '../data/Financial Sample.xlsx')
worksheet = workbook['Sheet1']
column_headers = []
for column in worksheet.iter_cols(min_row = 1, max_row = 1, values_only = True):
column_headers.extend(column)
print('Header')
for index, header in enumerate(column_headers, start = 1):
print(f"{header}", end = ' | ')
else:
print(end = '\n')
print('\nContent')
for row in worksheet.iter_rows(min_row = 2, max_row = 4, values_only = True):
for index, value in enumerate(row, start = 1):
print(f"{value}", end = ' | ')
else:
print(end = '\n')
workbook.close()
import openpyxl
workbook = openpyxl.load_workbook(filename = '../data/Financial Sample.xlsx')
worksheet = workbook['Sheet1']
column_headers = []
for column in worksheet.iter_cols(min_row = 1, max_row = 1, values_only = True):
column_headers.extend(column)
print('Header')
for index, header in enumerate(column_headers, start = 1):
print(f"{header}", end = ' | ')
else:
print(end = '\n')
print('\nContent')
for row in worksheet.iter_rows(min_row = 2, max_row = 4, values_only = True):
for index, value in enumerate(row, start = 1):
print(f"{value}", end = ' | ')
else:
print(end = '\n')
workbook.close()
Header Segment | Country | Product | Discount Band | Units Sold | Manufacturing Price | Sale Price | Gross Sales | Discounts | Sales | COGS | Profit | Date | Month Number | Month Name | Year | Content Government | Canada | Carretera | None | 1618.5 | 3 | 20 | 32370 | 0 | 32370 | 16185 | 16185 | 2014-01-01 00:00:00 | 1 | January | 2014 | Government | Germany | Carretera | None | 1321 | 3 | 20 | 26420 | 0 | 26420 | 13210 | 13210 | 2014-01-01 00:00:00 | 1 | January | 2014 | Midmarket | France | Carretera | None | 2178 | 3 | 15 | 32670 | 0 | 32670 | 21780 | 10890 | 2014-06-01 00:00:00 | 6 | June | 2014 |