Advertisement
teslariu

archivos python

Nov 18th, 2022
1,020
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.99 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4. # funciones de manjeo de archivo: open, close, read, readlines, write,
  5. # writelines. readline, writeline, etc
  6. """
  7. ========= ===============================================================
  8. Character Meaning
  9. --------- ---------------------------------------------------------------
  10. 'r'       open for reading (default)
  11. 'w'       open for writing, truncating the file first
  12. 'x'       create a new file and open it for writing
  13. 'a'       open for writing, appending to the end of the file if it exists
  14. 'b'       binary mode
  15. 't'       text mode (default)
  16. '+'       open a disk file for updating (reading and writing)
  17. 'U'       universal newline mode (deprecated)
  18. ========= ===============================================================
  19. """
  20.  
  21. # Script que crea un archivo de temperaturas en ºC y luego crea otro
  22. # para guardar los datos convertidos a ºF
  23.  
  24. # creo un archivo vacio "celsius.txt" o lo abro
  25. try:
  26.     f = open("celsius.txt","x")
  27. except FileExistsError:
  28.     f = open("celsius.txt","a")
  29.  
  30.  
  31.  
  32. # creo una lista cuyos elementos seran los renglones del archivo de texto
  33. datos =["23ºC\n", "-12.5ºC\n", "0.2ºC\n", "14ºC\n"]
  34.  
  35. """
  36. Otra forma
  37. datos =["23ºC", "-12.5ºC", "0.2ºC", "14ºC"]
  38. for dato in datos:
  39.    f.write(dato + "\n")
  40. """
  41.  
  42.  
  43. # escribo los datos en el archivo
  44. f.writelines(datos)
  45.  
  46. # cierro el archivo
  47. f.close()
  48.  
  49. # Supongamos que me olvide un dato
  50. f = open("celsius.txt","a")
  51. f.write("11ºC\n")
  52. f.close()
  53.  
  54. # Abro en modo lectura para ver el contenido del archivo
  55. f = open("celsius.txt")
  56. print(f.read())
  57. f.close()
  58.  
  59. # creo el archivo farenheit
  60. f = open("farenheit.txt","x")
  61.  
  62. # abro celsius para leer el contenido actualizado
  63. f2 = open("celsius.txt")
  64.  
  65. # leo los datos de celsius
  66. datos = f2.readlines()
  67.  
  68. # convierto los datos uno por uno
  69. for dato in datos:
  70.     temp, escala = dato.split("º")
  71.     temp = float(temp) * 1.8 + 32
  72.     f.write(f"{temp:.1f}ºF\n")
  73.    
  74. # cierro los archivos
  75. f.close()
  76. f2.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement