teslariu

archivos texto

May 12th, 2023 (edited)
965
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.30 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. Funciones de manejo de archivo: open, write, read, writelines, readlines
  5.  
  6.  
  7. Resumen de open()
  8. ========= ===============================================================
  9. Character       Meaning
  10. --------- ---------------------------------------------------------------
  11.    'r'       open for reading (default)
  12.    'w'       open for writing, truncating the file first
  13.    'x'       create a new file and open it for writing
  14.    'a'       open for writing, appending to the end of the file if it exists
  15.    'b'       binary mode
  16.    't'       text mode (default)
  17.    '+'       open a disk file for updating (reading and writing)
  18.    'U'       universal newline mode (deprecated)
  19. ========= ===============================================================
  20.  
  21.    The default mode is 'rt' (open for reading text). For binary random
  22.    access, the mode 'w+b' opens and truncates the file to 0 bytes, while
  23.    'r+b' opens the file without truncation. The 'x' mode implies 'w' and
  24.    raises an `FileExistsError` if the file already exists.
  25.  
  26. """
  27. # Script que crea un archivo de texto con temp en ºC. Luego, crea otro
  28. # con las temp del primero convertidas a ºF
  29.  
  30. # Creo un archivo de texto vacío, le guardo los datos y lo cierro:
  31. try:
  32.     f = open("centigrados.txt", "x")
  33. except FileExistsError:
  34.     f = open("centrigrados.txt","a")
  35.    
  36.  
  37. datos = ["101ºC\n", "25.5ºC\n","11ºC\n","56ºC\n"]
  38.  
  39. f.writelines(datos)
  40.  
  41. # Despues de escribir, hay que cerrar:
  42. f.close()
  43.  
  44. # Supongo que me olvide de agregar un dato, entonces lo abro y lo añado
  45. f = open("centigrados.txt","a")
  46. f.write("100ºC\n")
  47.  
  48. # Si quiero ver los datos, debo cerrar el archivo y abrirlo en modo lectura
  49. f.close()
  50. f = open("centigrados.txt")
  51. print(f.read())
  52. f.close()
  53.  
  54. # creo el otro archivo
  55. try:
  56.     f2 = open("farenheit.txt","x")
  57. except FileExistsError:
  58.     f2 = open("farenheit.txt","a")
  59.  
  60. # leo los datos actualizados de centigrados.txt y lo cierro
  61. # f = open("centigrados.txt")
  62. # datos = f.readlines()
  63. # f.close()
  64. with open("centigrados.txt") as f:
  65.     datos = f.readlines()
  66.  
  67. # completo el archivo de farenheit
  68. for dato in datos:
  69.     temp, escala = dato.split("º")
  70.     temp = float(temp) * 1.8 + 32
  71.     f2.write(f"{temp:.1f}ºF\n")
  72.    
  73. # cierro el archivo
  74. f2.close()
  75.  
  76.  
Advertisement
Add Comment
Please, Sign In to add comment