Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- """
- Funciones de manejo de archivo: open, write, read, writelines, readlines
- Resumen de 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)
- ========= ===============================================================
- 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.
- """
- # Script que crea un archivo de texto con temp en ºC. Luego, crea otro
- # con las temp del primero convertidas a ºF
- # Creo un archivo de texto vacío, le guardo los datos y lo cierro:
- try:
- f = open("centigrados.txt", "x")
- except FileExistsError:
- f = open("centrigrados.txt","a")
- datos = ["101ºC\n", "25.5ºC\n","11ºC\n","56ºC\n"]
- f.writelines(datos)
- # Despues de escribir, hay que cerrar:
- f.close()
- # Supongo que me olvide de agregar un dato, entonces lo abro y lo añado
- f = open("centigrados.txt","a")
- f.write("100ºC\n")
- # Si quiero ver los datos, debo cerrar el archivo y abrirlo en modo lectura
- f.close()
- f = open("centigrados.txt")
- print(f.read())
- f.close()
- # creo el otro archivo
- try:
- f2 = open("farenheit.txt","x")
- except FileExistsError:
- f2 = open("farenheit.txt","a")
- # leo los datos actualizados de centigrados.txt y lo cierro
- # f = open("centigrados.txt")
- # datos = f.readlines()
- # f.close()
- with open("centigrados.txt") as f:
- datos = f.readlines()
- # completo el archivo de farenheit
- for dato in datos:
- temp, escala = dato.split("º")
- temp = float(temp) * 1.8 + 32
- f2.write(f"{temp:.1f}ºF\n")
- # cierro el archivo
- f2.close()
Advertisement
Add Comment
Please, Sign In to add comment