Advertisement
teslariu

archivos

Jan 16th, 2023
2,571
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.29 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. Funciones basicas de Python para manejo de archivos.
  5.  
  6. open(nombre,modo)  --> abre  y/o crea un archivo
  7. read(), readline(), readlines()  --> lee el contenido de un archivo
  8. write(), writeline(), writelines()  --> escribe en un archivo
  9. close()  --> cierra un archivo
  10.  
  11. extracto de help(open)
  12.  
  13. ========= ===============================================================
  14. Character Meaning
  15. --------- ---------------------------------------------------------------
  16. 'r'       open for reading (default)
  17. 'w'       open for writing, truncating the file first
  18. 'x'       create a new file and open it for writing
  19. 'a'       open for writing, appending to the end of the file if it exists
  20. 'b'       binary mode
  21. 't'       text mode (default)
  22. '+'       open a disk file for updating (reading and writing)
  23. 'U'       universal newline mode (deprecated)
  24. ========= ===============================================================
  25.  
  26.  
  27. Script que crea un archivo con temp. en ºC y otro en ºF a partir de los
  28. valores del primer archivo
  29. """
  30. # Creo una archivo vacío "celsius.txt"
  31. try:
  32.     f = open("celsius.txt","x")
  33. except FileExistsError:
  34.     pass
  35.  
  36. # Creo una lista para ingresar datos al archivo
  37. datos = ["18ºC\n", "-12.5ºC\n", "0ºC\n", "14.2ºC\n"]
  38.  
  39. # escribo el archivo
  40. f.writelines(datos)
  41.  
  42. # Supongamos que haya terminado de trabajar con el archivo, entonces lo cierro
  43. f.close()
  44.  
  45. # Abro el archivo nuevamente para agregarle un par de valores
  46. f = open("celsius.txt","a")
  47. datos = ["368ºC\n", "-100ºC\n"]
  48. f.writelines(datos)
  49.  
  50. # Imprimo en pantalla el contenido del archivo.
  51. # Para ello, debo leerlo. Como está en modo append primero lo cierro
  52. # y lo vuelvo a abrir en modo read
  53. f.close()
  54. f = open("celsius.txt")
  55. print(f.read())
  56.  
  57. # Creo un archivo vacío farenheit.txt
  58. f2 = open("farenheit.txt","x")
  59.  
  60. # leo todos los datos del archivo de celsius.txt
  61. # como ya lo había leído en la línea 55, el flujo se vació, debo cerrar
  62. # y volver a leer. Uso apertura con with: se cierra SOLO
  63. f.close()
  64.  
  65. with open("celsius.txt") as f:
  66.     datos = f.readlines()
  67.  
  68.  
  69. # convierto ºC -> ºF
  70. for dato in datos:
  71.     temp, escala = dato.split("º")
  72.     temp = float(temp) * 1.8 + 32
  73.     f2.write(f"{temp:.1f}ºF\n")
  74.    
  75. # cierro f2
  76. f2.close()
  77.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement