Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- """
- Funciones basicas de Python para manejo de archivos.
- open(nombre,modo) --> abre y/o crea un archivo
- read(), readline(), readlines() --> lee el contenido de un archivo
- write(), writeline(), writelines() --> escribe en un archivo
- close() --> cierra un archivo
- extracto de help(open)
- ========= ===============================================================
- 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)
- ========= ===============================================================
- Script que crea un archivo con temp. en ºC y otro en ºF a partir de los
- valores del primer archivo
- """
- # Creo una archivo vacío "celsius.txt"
- try:
- f = open("celsius.txt","x")
- except FileExistsError:
- pass
- # Creo una lista para ingresar datos al archivo
- datos = ["18ºC\n", "-12.5ºC\n", "0ºC\n", "14.2ºC\n"]
- # escribo el archivo
- f.writelines(datos)
- # Supongamos que haya terminado de trabajar con el archivo, entonces lo cierro
- f.close()
- # Abro el archivo nuevamente para agregarle un par de valores
- f = open("celsius.txt","a")
- datos = ["368ºC\n", "-100ºC\n"]
- f.writelines(datos)
- # Imprimo en pantalla el contenido del archivo.
- # Para ello, debo leerlo. Como está en modo append primero lo cierro
- # y lo vuelvo a abrir en modo read
- f.close()
- f = open("celsius.txt")
- print(f.read())
- # Creo un archivo vacío farenheit.txt
- f2 = open("farenheit.txt","x")
- # leo todos los datos del archivo de celsius.txt
- # como ya lo había leído en la línea 55, el flujo se vació, debo cerrar
- # y volver a leer. Uso apertura con with: se cierra SOLO
- f.close()
- with open("celsius.txt") as f:
- datos = f.readlines()
- # convierto ºC -> ºF
- for dato in datos:
- temp, escala = dato.split("º")
- temp = float(temp) * 1.8 + 32
- f2.write(f"{temp:.1f}ºF\n")
- # cierro f2
- f2.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement