Advertisement
teslariu

archivos

Nov 6th, 2021
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.98 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. ========= ===============================================================
  5. Character Meaning
  6. --------- ---------------------------------------------------------------
  7. 'r'       open for reading (default)
  8. 'w'       open for writing, truncating the file first
  9. 'x'       create a new file and open it for writing
  10. 'a'       open for writing, appending to the end of the file if it exists
  11. 'b'       binary mode
  12. 't'       text mode (default)
  13. '+'       open a disk file for updating (reading and writing)
  14. 'U'       universal newline mode (deprecated)
  15. ========= ===============================================================
  16.  
  17. funciones para manejar archivos: open(), read(), write(), close()
  18. readlines(), writelines(), ....
  19. """
  20. # Script que crea un archivo con temperaturas en ºC, luego crea otro
  21. # archivo y lo llena con el equivalente del primero pero expresado en
  22. # ºF
  23.  
  24. # creo un archivo vacío "celsius.txt"
  25. f = open("celsius.txt", "x")
  26.  
  27. # creo una lista con los datos a guardar en el archivo
  28. datos = ["20ºC\n", "11ºC\n", "15.2ºC\n", "-10.7ºC\n"]
  29.  
  30. # escribo los datos en el archivo
  31.  
  32. # modo 1: con write()
  33. #for dato in datos:
  34. #   f.write(dato)
  35.  
  36. # modo 2: con writelines()
  37. f.writelines(datos)
  38.  
  39. # cierro el archivo
  40. f.close()
  41.  
  42. # supongamos que nos olvidamos de un dato, hay que agregarlo
  43. f = open("celsius.txt", "a")
  44. f.write("100ºC\n")
  45.  
  46. # creo el archivo "farenheit.txt"
  47. f2 = open("farenheit.txt", "x")
  48.  
  49. # tengo que ller los valores de "celsius.txt" y convertirlos a ºF
  50. # tengo que cerrar el archivo y abrirlo en modo lectura
  51. f.close()
  52. f = open("celsius.txt")
  53.  
  54. # creo una lista leyendo todos los valores de temp de "celsius.txt"
  55. datos = f.readlines()
  56.  
  57. # leo uno por uno cada dato lo convierto y lo escribo
  58. # en "farenheit.txt"
  59. for dato in datos:
  60.     temp, escala = dato.split("º")
  61.     temp = float(temp) * 1.8 + 32
  62.     f2.write("{:.1f}ºF\n".format(temp))
  63.    
  64. # cierro todos los archivos
  65. f.close()
  66. f2.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement