Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- #
- """
- funciones para archivo: open(), read(), write(), close()
- ========= ===============================================================
- Character Meaning
- --------- ---------------------------------------------------------------
- 'r' open for reading (default)
- 'w' open for writing, truncating the file first
- 'x' create a new file and open it for writing
- 'a' open for writing, appending to the end of the file if it exists
- 'b' binary mode
- 't' text mode (default)
- '+' open a disk file for updating (reading and writing)
- 'U' universal newline mode (deprecated)
- ========= ===============================================================
- The default mode is 'rt' (open for reading text).
- """
- # Script que crea un archivo de texto con temperaturas en ºC
- # y otro con las mismas temperaturas expresadas en ºF
- # creo un archivo vacio 'celsius.txt' para escritura
- f = open('celsius.txt','x')
- # creo una lista con los datos para agregar al archivo
- datos = ["20ºC\n", "-15ºC\n", "11ºC\n", "0ºC\n"]
- # escribo los datos en el archivo
- f.writelines(datos)
- """
- otra forma:
- for dato in datos:
- f.write(dato)
- """
- # cierro el archivo porque termine de guardar los datos
- f.close()
- # abro de nuevo para agregar otro dato
- f = open("celsius.txt","a")
- f.write("100ºC\n")
- f.close()
- #agrego una dato arriba de todo
- #primero abro(modo lectura)para leer los valores
- f = open("celsius.txt")
- datos = f.readlines()
- f.close()
- # ahora abro modo escritura para escribir los valores
- f = open("celsius.txt","w")
- datos.insert(0,"33ºC\n")
- f.writelines(datos)
- f.close()
- # creo un archivo vacio 'farenheit.txt' para escritura
- f = open('farenheit.txt','x')
- # convierto los datos a farenheit y los grabo
- for dato in datos:
- temp, escala = dato.split("º")
- temp = float(temp) * 1.8 + 32
- f.write("{:.1f}ºF\n".format(temp))
- # cierro el archivo
- f.close()
- """
- f = open("demo.txt")
- print(f.read()) --> imprime todo el contenido de demo.txt
- print(f.readline()) --> imprime una linea
- Manera recomendada para abrir archivos, modificarlo/añadir contenido
- with open("demo.txt","a") as f: # equivale a f = open("demo.txt","a")
- f.write("nueva linea\n")
- (se cierra automaticamente, no necesita close()
- """
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement