You are on page 1of 5

Lectura de archivos

Algoritmos y Programación 2568364


Departamento de Ingeniería Eléctrica
Facultad de Ingeniería
2017-2

Funciones Informática I (2016-2)


Input and Output
Recordemos que, un algoritmo es un proceso
preciso, computable y finito, que paso a paso
lleva a la solución de un problema.

Todo algoritmo debe tener tres partes:

Inputs Process Outputs

Files Files
Lectura de archivos Algoritmos y Programación 2
Read and write files
open: Open file and return a corresponding file
object.
Character Meaning

'r' open for reading (default)

'w' open for writing, truncating the file first

'x' open for exclusive creation, failing if the file already exists

'a' open for writing, appending to the end of the file if it exists

'r+' open for read and write

https://docs.python.org/3.5/library/functions.html#open

Lectura de archivos Algoritmos y Programación 3


Files
file
file == open('names.txt',
open('names.txt', 'r')
'r') Imprime:
for
for line
line in
in file:
file: Carlos
print(line)
print(line)
file.close()
file.close() Pedro
file
file == open('names.txt',
open('names.txt', 'w')
'w') Imprime:
file.write('Juan\n')
file.write('Juan\n') Juan
file.write('Ana\n')
file.write('Ana\n') Ana
file.close()
file.close()
file
file == open('names.txt',
open('names.txt', 'r')
'r')
for
for line
line in
in file:
file:
print(line[:-1])
print(line[:-1])
file.close()
file.close()

file
file == open('names.txt',
open('names.txt', 'a')
'a') Imprime:
file.write('Clara\n')
file.write('Clara\n') Juan
file.write('Julia\n')
file.write('Julia\n') Ana
file.close()
file.close() Clara
file
file == open('names.txt',
open('names.txt', 'r')
'r') Julia
for
for line
line in
in file:
file:
print(line[:-1])
print(line[:-1])
file.close()
file.close()

Lectura de archivos Algoritmos y Programación 4


Files
file
file == open('names.txt','r')
open('names.txt','r') Imprime:
for
for line
line in
in file:
file: Andres
print(line[:-1])
print(line[:-1]) Pedro
file.close()
file.close()

file
file == open('names.txt','r+')
open('names.txt','r+') Imprime:
file.write('Ana')
file.write('Ana') Anares
file.close()
file.close() Pedro

file
file == open('names.txt','r')
open('names.txt','r')
for
for line
line in
in file:
file:
print(line[:-1])
print(line[:-1])
file.close()
file.close()

Lectura de archivos Algoritmos y Programación 5

You might also like