Diferencia entre revisiones de «Curso de Programación en Python/File IO»

De WikiCabal
Ir a la navegación Ir a la búsqueda
(Leer archivo en modo binary - LeerArchivo-7.py)
 
(Sin diferencias)

Revisión actual del 21:55 16 dic 2015

Usando Archivos en Python

Open()

La sintaxis es:
objeto_de_Archivo = open( NombreDeArchivo, modo, encoding )

Modo

El argumento de modo es opcional. Si no está, el modo es 'r' ( Leer ).

Los modos pueden ser:

'r' Abrir solo para leer

'w' Abrir solo para escribir. Si existe el archivo, sus contenidos se borran.

'a' Abrir para escribir al fin de un archivo sin borar sus contenidos. 

'r+' Abrir para leer y también para escribir.

Crear un Archivo de texto - CrearArchivo-1.py

 1 #!/usr/bin/python3
 2 #-*-coding: utf-8 -*-
 3 
 4 MiArchivo = open( "NuevoArchivo.txt", "w", encoding='utf-8' )
 5 
 6 MiArchivo.write( "Es mi primer archivo\n")
 7 
 8 MiArchivo.write("creado en Python\n")
 9 
10 MiArchivo.close()

Resultado

[rrc@Llawyr PythonClase]$ ls -al NuevoArchivo.txt 
-rw------- 1 rrc rrc 38 Oct  3 13:07 NuevoArchivo.txt

[rrc@Llawyr PythonClase]$ cat NuevoArchivo.txt 
Es mi primer archivo
creado en Python

Agregar texto a un Archivo existente - AgregarEnArchivo-1.py

 1 #!/usr/bin/python3
 2 #-*-coding: utf-8 -*-
 3 
 4 MiArchivo = open( "NuevoArchivo.txt", "a", encoding='utf-8' )
 5 
 6 MiArchivo.write( "Estamos agregando los líneas de texto al fin de NuevoArchivo.txt\n")
 7 
 8 MiArchivo.write("si todo sirve cómo pensamos\n")
 9 
10 MiArchivo.close()

Resultado

[rrc@Llawyr PythonClase]$ ls -al NuevoArchivo.txt 
-rw------- 1 rrc rrc 38 Oct  3 13:07 NuevoArchivo.txt
[rrc@Llawyr PythonClase]$ cat NuevoArchivo.txt 
Es mi primer archivo
creado en Python
[rrc@Llawyr PythonClase]$ ./AgregarEnArchivo-1.py 
[rrc@Llawyr PythonClase]$ ls -al NuevoArchivo.txt 
-rw------- 1 rrc rrc 133 Oct  3 15:06 NuevoArchivo.txt
[rrc@Llawyr PythonClase]$ cat NuevoArchivo.txt 
Es mi primer archivo
creado en Python
Estamos agregando los líneas de texto al fin de NuevoArchivo.txt
si todo sirve cómo pensamos

Cómo leer de un archivo de texto

Son diferentes manera a leer un archivo.

file.read() - LeerArchivo-1.py

Si quieres leer todos los caracteres de un archivo puedes usar file.read().

1 #!/usr/bin/python3
2 #-*-coding: utf-8 -*-
3 
4 ArchivoALeer = open( 'NuevoArchivo.txt', 'r', encoding='utf-8' )
5 
6 print( ArchivoALeer.read() )
7 ArchivoALeer.close()

Resultado

[rrc@Llawyr PythonClase]$ ./LeerArchivo-1.py
Es mi primer archivo
creado en Python
Estamos agregando los líneas de texto al fin de NuevoArchivo.txt
si todo sirve cómo pensamos

file.read( n ) - LeerArchivo-2.py

Puedes especificar cuantos caracteres a leer usando file.read( n ).

1 #!/usr/bin/python3
2 #-*-coding: utf-8 -*-
3 
4 ArchivoALeer = open( 'NuevoArchivo.txt', 'r', encoding='utf-8' )
5 
6 print( ArchivoALeer.read( 12 ) )
7 ArchivoALeer.close()

Resultado

[rrc@Llawyr PythonClase]$ ./LeerArchivo-2.py
Es mi primer

file.readline() - LeerArchivo-3.py

Puedes leer una línea a la ves usando file.readline(n).

1 #!/usr/bin/python3
2 #-*-coding: utf-8 -*-
3 
4 ArchivoALeer = open( 'NuevoArchivo.txt', 'r', encoding='utf-8' )
5 print( "Usando readline() la primera ves:" )
6 print( ArchivoALeer.readline() )
7 print( "Usando readline() la segunda ves:" )
8 print( ArchivoALeer.readline() )
9 ArchivoALeer.close()

Resultado

[rrc@Llawyr PythonClase]$ ./LeerArchivo-3.py
Usando readline() la primera ves:
Es mi primer archivo

Usando readline() la segunda ves:
creado en Python

file.readlines() - LeerArchivo-4.py

file.readlines() regresa el archivo completo en una lista de cadenas.

1 #!/usr/bin/python3
2 #-*-coding: utf-8 -*-
3 
4 ArchivoALeer = open( 'NuevoArchivo.txt', 'r', encoding='utf-8' )
5 print( ArchivoALeer.readlines() )
6 ArchivoALeer.close()

Resultado

[rrc@Llawyr PythonClase]$ ./LeerArchivo-4.py
['Es mi primer archivo\n', 'creado en Python\n', 'Estamos agregando los líneas de texto al fin de NuevoArchivo.txt', 
'si todo sirve cómo pensamos']

Leer un archivo con un loop - LeerArchivo-5.py

1 #!/usr/bin/python3
2 #-*-coding: utf-8 -*-
3 
4 ArchivoALeer = open( 'NuevoArchivo.txt', 'r', encoding='utf-8' )
5 
6 for line in ArchivoALeer:
7   print( line )
8 
9 ArchivoALeer.close()

Resultado

[rrc@Llawyr PythonClase]$ ./LeerArchivo-5.py
Es mi primer archivo

creado en Python

Estamos agregando los líneas de texto al fin de NuevoArchivo.txt

si todo sirve cómo pensamos

Crear un archivo usando with - CrearArchivo-2.py

1 #!/usr/bin/python3
2 #-*-coding: utf-8 -*-
3 
4 with open( 'NuevoArchivo3.txt', 'w', encoding='utf-8' ) as f:
5   f.write( "Estamos escibiendo en NuevoArchivo3 " )
6   f.write( "Usando with.\nNo está necesario usar f.close cuando usas with.\n" )
7   f.write( "El sabe cómo cerrar el archivo sin instrucción, " )
8   f.write( "y se obtiene mejor sintaxis y manejo de excepciones" )

Resultado

[rrc@Llawyr PythonClase]$ ./CrearArchivo-2.py 
[rrc@Llawyr PythonClase]$ ls -al NuevoArchivo3.txt 
-rw------- 1 rrc rrc 197 Oct  3 15:29 NuevoArchivo3.txt
[rrc@Llawyr PythonClase]$ cat NuevoArchivo3.txt 
Estamos escibiendo en NuevoArchivo3 Usando with.
No está necesario usar f.close cuando uasas with.
El sabe a cerrar el archivo sin instrucción, y se obtiene mejor sintaxis y manejo de excepciones

Leer los contenidos de un archivo en una lista usando with - LeerArchivo-6.py

1 #!/usr/bin/python3
2 #-*-coding: utf-8 -*-
3 
4 with open( "NuevoArchivo3.txt", encoding='utf-8' ) as f:
5   data = f.readlines()
6 
7 print( type( data ) )
8 print( data )

Resultado

[rrc@Llawyr PythonClase]$ ./LeerArchivo-6.py
['Estamos escibiendo en NuevoArchivo3 Usando with.\n', 'No está necesario usar f.close cuando uasas with.\n', 'El sabe a cerrar el archivo sin instrucción, y se obtiene mejor sintaxis y manejo de excepciones']

Leer los contenidos de un archivo en una lista usando with - LeerArchivo-6a.py

1 #!/usr/bin/python3
2 #-*-coding: utf-8 -*-
3 
4 with open( 'UniCodeArchivo.txt', 'r', encoding='utf-8' ) as ArchivoALeer:
5   print( ArchivoALeer.read( 12 ) )
6 with open( 'UniCodeArchivo.txt', 'rb' ) as ArchivoALeer:
7   print( ArchivoALeer.read( 12 ) )

Resultado

[rrc@Pridd PythonClase]$ ./LeerArchivo-6a.py 
á é í ó ú ñ Á É Í 
b'\xc3\xa1 \xc3\xa9 \xc3\xad \xc3\xb3 \xc3\xba \xc3\xb1 '

Leer archivo en modo binary - LeerArchivo-7.py

1 #!/usr/bin/python3
2 #-*-coding: utf-8 -*-
3 
4 with open( 'NuevoArchivo.txt', encoding='utf-8' ) as f:
5   data = f.readlines()
6 
7 for line in data:
8   words = line.split()
9   print( words )

Resultado

[rrc@Llawyr PythonClase]$ ./LeerArchivo-7.py 
['Es', 'mi', 'primer', 'archivo']
['creado', 'en', 'Python']
['Estamos', 'agregando', 'los', 'líneas', 'de', 'texto', 'al', 'fin', 'de', 'NuevoArchivo.txt']
['si', 'todo', 'sirve', 'cómo', 'pensamos']

Leer archivo con seek y tell - LeerArchivo-8.py

 1 #!/usr/bin/python3
 2 #-*-coding: utf-8 -*-
 3 
 4 with open( "SeekArchivo.txt", encoding='utf-8') as fh:
 5   print( "fh.tell() nos da:", fh.tell() )
 6   print( "fh.read(8) nos da:", fh.read(8) )
 7   print( "fh.tell() nos da:", fh.tell() )
 8   print( "fh.seek( fh.tell() + 1 ) nos da:", fh.seek( fh.tell() + 1 ) )
 9   print( "fh.tell() nos da:", fh.tell() )
10   print( "fh.read() nos da:", fh.read() )
11   print( "fh.tell() nos da:", fh.tell() )
12   print( "fh.seek( fh.tell() - 18 ) nos da:", fh.seek( fh.tell() - 18 ) )
13   print( "fh.read( 6 ) nos da:", fh.read( 6 ) )

Resultado

[rrc@Llawyr PythonClase]$ ./LeerArchivo-8.py 
fh.tell() nos da: 0
fh.read(8) nos da: En estos
fh.tell() nos da: 8
fh.seek( loc + 1 ) nos da: 9
fh.tell() nos da: 9
fh.read() nos da: tiempos se necesita mucho ingenio para cometer un pecado original. 

fh.tell() nos da: 77
fh.seek( loc - 18 ) nos da: 59
fh.read( 6 ) nos da: pecado