Advertisement
teslariu

archivos

Oct 18th, 2021
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.19 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # funciones importantes para manejo de archivos:
  5. # open(), read(), write(), close()
  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. The default mode is 'rt' (open for reading text). For binary random
  21. access, the mode 'w+b' opens and truncates the file to 0 bytes, while
  22. 'r+b' opens the file without truncation. The 'x' mode implies 'w' and
  23. raises an `FileExistsError` if the file already exists.
  24.  
  25. Script que crea un archivo de texto con temp en ºC y otro vacío, luego
  26. leo el contenido del archivo con temp enºC y las paso a ºF para guardarlas
  27. en el segundo archivo
  28.  
  29. """
  30. ####### creo el archivo vacío, le guardo datos y lo cierro
  31. f = open("centigrados.txt","x")
  32. datos = ['10ºC\n', '13ºC\n', '-15.2ºC\n', '-24.1ºC\n']
  33.  
  34. # Método 1: usando write()
  35. for dato in datos:
  36. f.write(dato)
  37.  
  38. # Método 2: usando writelines()
  39. # f.writelines(datos)
  40.  
  41. f.close()
  42.  
  43. ###### creo el segundo archivo
  44. f = open("farenheit.txt","x")
  45.  
  46. # abro el primer archivo para leer los datos
  47. f2 = open("centigrados.txt")
  48. temperaturas = f2.readlines()
  49.  
  50.  
  51. # guardo los datos en el segundo archivo (ºF):
  52. for linea in temperaturas:
  53. temp, escala = linea.split("º")
  54. temp = float(temp) * 1.8 + 32
  55. f.write("{:.1f}ºF\n".format(temp))
  56.  
  57. # muestro el contenido de farenheit.txt
  58. # como esta en modo escritura, tengo que cerrarlo
  59. # y abrirlo nuevamente en modo lectura:
  60. f.close()
  61. f = open("farenheit.txt")
  62. valores = f.readlines()
  63. for linea in valores:
  64. print(linea.strip())
  65.  
  66.  
  67. # cierro los archivos
  68. f.close()
  69. f2.close()
  70.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement