Advertisement
teslariu

archivos

Oct 2nd, 2021
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.98 KB | None | 0 0
  1. """
  2. Existen 3 funciones básicas para archivos:
  3. open() -> abre un archivo
  4. read() -> lee el archivo
  5. write() -> escribe una línea en el archivo
  6.  
  7. Otras:
  8. readline -> lee una línea del archivo
  9. readlines -> lee todas las líneas del archivo
  10. writelines -> escribe todas las líneas en el archivo
  11. close -> cierra el archivo
  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. Script que lee un archivo con temperaturas expresadas en ºC y las convierte a ºF. Debe crear
  26. previamente el archivo con temp. en Celsius y guardar también el archivo en ºF
  27. """
  28. # creo el archivo con temp en ºC:
  29. f = open("centigrados.txt","x")
  30.  
  31. # creo una lista con los datos
  32. datos = ['10ºC\n', '125.2ºC\n', '0.25ºC\n', '14.5ºC\n', '-14.02ºC\n']
  33.  
  34. # escribo los datos en el archivo
  35. f.writelines(datos)
  36.  
  37. # cierro el archivo centígrados
  38. f.close()
  39.  
  40. # creo el archivo con temp en ºF:
  41. f = open("farenheit.txt","x")
  42.  
  43. # convierto línea a línea y escribo en "farenheit.txt"
  44. for linea in datos:
  45.     temp, escala = linea.split("º")
  46.     temp = float(temp) * 1.8 + 32
  47.     f.write("{:.1f}ºF\n".format(temp))
  48.  
  49. # cierro el archivo
  50. f.close()
  51.  
  52. ## adicional: supongamos que tengo que agregar un valor (15ºC) a "centigrados.txt"
  53. f = open("centigrados.txt","a")
  54. f.write("15ºC\n")
  55. f.close()
  56. temp = 15 * 1.8 + 32
  57. f = open("farenheit.txt","a")
  58. f.write("{:.1f}ºF\n".format(temp))
  59. f.close()
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement