Advertisement
teslariu

archivos de texto

Sep 7th, 2022
986
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.33 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. Ayuda de open()
  5. ========= ===============================================================
  6. Character Meaning
  7. --------- ---------------------------------------------------------------
  8. 'r'       open for reading (default)
  9. 'w'       open for writing, truncating the file first
  10. 'x'       create a new file and open it for writing
  11. 'a'       open for writing, appending to the end of the file if it exists
  12. 'b'       binary mode
  13. 't'       text mode (default)
  14. '+'       open a disk file for updating (reading and writing)
  15. 'U'       universal newline mode (deprecated)
  16. ========= ===============================================================
  17.  
  18. ## funciones para trabajar con archivos
  19. open()  --> abre un archivo
  20. read()  --> lee el contenido de un archivo (readline, readlines)
  21. write() --> escribe contenido en un archivo (writeline, writelines)
  22. close()  --> cerrar archivos
  23. """
  24. # 1) Crear un archivo "celsius.txt" con valores de temperaturas en ºC
  25. # 2) Abrir el archivo anterior, añadirle datos e imprimir su contenido
  26. # 3) Crear un archivo "farenheit.txt" y completarlo con los valores de
  27. #   celsius.txt convertidos a ºF
  28.  
  29. # Creo un archivo "celsius.txt". La función open() abre un archivo o lo crea
  30. f = open("celsius.txt","x")
  31.  
  32.  
  33. # Creo una lista con los renglones del archivo:
  34. datos = ["25.8ºC\n", "-11.51ºC\n", "0.22ºC\n", "34.8ºC\n", "14.08ºC\n", "-1ºC\n",]
  35.  
  36. # añado los datos al archivo
  37. # for dato in datos():
  38. #     f.write(dato)
  39. f.writelines(datos)
  40.  
  41. # cierro el archivo
  42. f.close()
  43.  
  44. # abro nuevamente el archivo para agregarle datos
  45. f = open("celsius.txt","a")
  46. datos = ["100.5ºC\n", "9.08ºC\n"]
  47. f.writelines(datos)
  48.  
  49. # imprimo los datos. Primero debo cerrar y luego abrir en modo lectura
  50. # para poder imprimir
  51. f.close()
  52. f = open("celsius.txt")
  53. print(f.read())
  54.  
  55.  
  56. # vuelco el contenido del archivo "celsius.txt" a una variable
  57. # en la línea 53, al imprimir f se queda sin datos. Debo leerlos nuevamente
  58. f.close()
  59. f = open("celsius.txt")
  60. datos = f.readlines()
  61. f.close()
  62.  
  63.  
  64. # creo el archivo farenheit.txt
  65. f = open("farenheit.txt","x")
  66.  
  67. # convierto los datos a ºF y los escribo en el archivo correspondiente
  68. for dato in datos:
  69.     temp, escala = dato.split("º")
  70.     temp = float(temp) * 1.8 + 32
  71.     f.write(f"{temp:.1f}ºF\n")
  72.    
  73. # cierro el archivo
  74. f.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement