Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- """
- ========================================================================
- 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.
- Funciones de manejo de archivo:
- open() --> abrir archivos
- read() --> leer el contenido
- readline() --> leer una línea
- readlines() --> leer todas las líneas y guardarlas en un lista
- write() --> escribir en un archivo (también hay writeline, etc)
- close() --> cierra el archivo
- """
- # Abro un archivo prueba.txt ya existente para lectura:
- f = open("prueba.txt")
- # leo su contenido y lo imprimo
- print(f.read())
- print()
- # imprimo una sola linea
- f = open("prueba.txt")
- print(f.readline())
- # usando readlines()
- f = open("prueba.txt")
- print(f.readlines())
- print()
- # como leer 2 lineas:
- f = open("prueba.txt")
- for i in range(1,3):
- print(f.readline(), end="")
- # si quiero agregar algo:
- f = open("prueba.txt", "a")
- f.write("Mercedes\n")
- # muestro el contenido
- f = open("prueba.txt")
- print(f.read())
- print()
- # si quiero agregar algo BORRANDO LO QUE HUBIERA:
- f = open("prueba.txt", "w")
- f.writelines(["Uno\n","Dos\n","Tres\n"])
- print()
- # muestro el contenido
- f = open("prueba.txt")
- print(f.read())
- print()
- """
- # crear un archivo nuevo y agregar datos
- alumnos = {"Alejandro":2, "Luis":3, "Ana":4}
- f = open("salida_script.txt", "x")
- for nombre, curso in alumnos.items():
- f.write(f"El alumno {nombre} está inscripto en {curso} cursos\n")
- # cierro el archivo:
- f.close()
- """
- # otra forma preferida de abrir archivos para escribirlos
- nombre = "Miguel"
- cursos = 10
- with open("salida_script.txt", "a") as f:
- f.write(f"El alumno {nombre} está inscripto en {cursos} cursos\n")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement