Advertisement
teslariu

files

Oct 20th, 2021
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.06 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4.  
  5. funciones importantes: open(), write(), writelines(), read()
  6.                       readlines(), close()
  7.  
  8. ========= ===============================================================
  9. Character Meaning
  10. --------- ---------------------------------------------------------------
  11. 'r'       open for reading (default)
  12. 'w'       open for writing, truncating the file first
  13. 'x'       create a new file and open it for writing
  14. 'a'       open for writing, appending to the end of the file if it exists
  15. 'b'       binary mode
  16. 't'       text mode (default)
  17. '+'       open a disk file for updating (reading and writing)
  18. 'U'       universal newline mode (deprecated)
  19. ========= ===============================================================
  20.  
  21. The default mode is 'rt' (open for reading text). For binary random
  22. access, the mode 'w+b' opens and truncates the file to 0 bytes, while
  23. 'r+b' opens the file without truncation. The 'x' mode implies 'w' and
  24. raises an `FileExistsError` if the file already exists.
  25. """
  26.  
  27. # Creo un archivo de texto vacío "centigrados.txt"
  28. f = open("centigrados.txt", "x")
  29.  
  30. # creo una lista de datos para agregarle al archivo
  31. datos = ["23ºC\n", "-14ºC\n", "12ºC\n", "11ºC\n"]
  32.  
  33. # guardo los datos:
  34.  
  35. # manera 1:
  36. # for dato in datos:
  37. #      f.write(dato)
  38.  
  39. # manera 2
  40. f.writelines(datos)
  41.  
  42. # cierro el archivo
  43. f.close()
  44.  
  45. # supongamos que lo quiero abrir para agregarle un dato -0.25ºC
  46. f = open("centigrados.txt","a")
  47.  
  48. # le agrego un dato
  49. f.write("-0.25ºC")
  50.  
  51. # creo otro archivo "farenheit.txt"
  52. f2 = open("farenheit.txt", "x")
  53.  
  54. # quiero leer los datos de "centigrados.txt" y pasarlos a "farenheit.txt"
  55. # debo cerrar centigrados.txt y abrirlo en modo lectura
  56. f.close()
  57. f = open("centigrados.txt")
  58.  
  59. # leo los datos de centigrados.txt
  60. datos = f.readlines()
  61.  
  62. # transformo cada lina a farenheit y la escribo en el archivo correspondiente
  63. for dato in datos:
  64.     temp, escala = dato.split("º")
  65.     temp = float(temp) * 1.8 + 32
  66.     f2.write("{:.1f}ºF\n".format(temp))
  67.  
  68. # cierro todo
  69. f.close()
  70. f2.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement