Advertisement
teslariu

archivos

Feb 17th, 2022
938
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.88 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. parte de help(open)
  5.  
  6. ========= ===============================================================
  7. Character Meaning
  8. --------- ---------------------------------------------------------------
  9. 'r'       open for reading (default)
  10. 'w'       open for writing, truncating the file first
  11. 'x'       create a new file and open it for writing
  12. 'a'       open for writing, appending to the end of the file if it exists
  13. 'b'       binary mode
  14. 't'       text mode (default)
  15. '+'       open a disk file for updating (reading and writing)
  16. 'U'       universal newline mode (deprecated)
  17. ========= ===============================================================
  18.  
  19. Script que lee un archivo con temperaturas expresadas en ºC, las
  20. convierte en ºF y las guarda en otro archivo
  21.  
  22. """
  23. # creo un archivo vacío 'celsius.txt'
  24. try:
  25.     f = open("celsius.txt", "x")
  26. except FileExistsError:
  27.     f = open("celsius.txt", "a")
  28.  
  29. # creo una lista con los renglones a escribir
  30. datos = ["23.3ºC\n", "-25.6ºC\n", "11.5ºC\n", "0ºC\n"]
  31.  
  32. # escribo los datos en el archivo
  33. """
  34. Una forma, escribiendo dato por dato con un for
  35.  
  36. for dato in datos:
  37.     f.write(dato)
  38. """
  39. f.writelines(datos)
  40.  
  41. # cierro el archivo
  42. f.close()
  43.  
  44. # creo un archivo vacío 'farenheit.txt'
  45. try:
  46.     f = open("farenheit.txt", "x")
  47. except FileExistsError:
  48.     f = open("farenheit.txt", "a")
  49.    
  50.  
  51. # leo un dato en ºC , lo paso a ºF y lo agrego al archivo "farenheit.txt"
  52. for dato in datos:
  53.     temp, escala = dato.strip().split("º")
  54.     temp = float(temp) * 1.8 + 32
  55.     f.write(f"{temp:.1f}ºF\n")
  56.    
  57. # cierro el archivo
  58. f.close()
  59.  
  60. # Abro celsius, borro el contenido y le escribo un valor
  61. # f = open("celsius.txt", "w")
  62. # f.write("BORRADO\n")
  63. # f.close() # debe usarse SI o SI
  64.  
  65. # lo mismo pero con "with" (no necesita close(), se cierra solo)
  66. with open("celsius.txt", "w") as f:
  67.     f.write("BORRADO\n")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement