-
Notifications
You must be signed in to change notification settings - Fork 0
F. Files
-
π When we want to read or write a file (say on your hard drive), we first must open the file. Opening the file communicates with your operating system, which knows where the data for each file is stored.
-
π If the open is successful, the operating system returns us a file handle. The file handle is not the actual data.
-
π If the file does not exist, open will fail.
MyF = open(βfilename.txtβ)
Puedes especificar el modo utilizado para abrir un archivo al pasar un segundo argumento a la funciΓ³n open. Enviar "r" significa modo de lectura, el cual es el predeterminado. Enviar "w" significa modo de escritura, para reescribir los contenidos de un archivo. Enviar "a" significa modo de anexo, para agregar nuevo contenido al final de un archivo.
Agregar "b" a un modo lo abre en modo binario, que es utilizado para archivos que no son texto (tales como archivos de imagen o sonido).
# write mode
open("filename.txt", "w")
# read mode
open("filename.txt", "r")
open("filename.txt")
# binary write mode
open("filename.txt", "wb")
### Modes
# w Write mode, overwritten
# r Read
# a Append
Puedes utilizar el signo + con cada uno de los modos de arriba para darles acceso adicional a archivos. Por ejemplo, r+ abre el archivo tanto para lectura como para escritura.
Una vez que un archivo haya sido abierto y utilizado, deberΓas cerrarlo. Esto se logra con el mΓ©todo close de un objeto archivo.
file = open("filename.txt", "w")
# do stuff to the file
file.close()
file = open("ToDo.txt","w")
file.write("Jane\n")
file.write("Mery\n")
file.write("Chris Hemsworth\n")
file.close()
file = open("ToDo.txt","r")
line = file.readline()
print(file.read())
file.close()
file = open("ToDo.txt","r")
line = file.readline()
data = file.read()
file.close()
print(data)
file = open("ToDo.txt","a")
file.write("Rihanna")
file.close()
file = open("ToDo.txt","r")
for line in file:
print(line, end = '')
file.close()
with open('photo.jpg', 'r+') as file_handle:
jpg_data = file_handle.read()
file_handle.close
f = open("demofile.txt")
# Same as
f = open("demofile.txt", "rt")
To read the file, pass in r
To read and write the file, pass in r+ w+
To read the binary file, pass in rb
To read the text file, pass in rt
To overwrite the file, pass in w
To append to the file, pass in a
To create a file, error if exist x
file.close() file.close() file.close()
f = open("demofile.txt", "wb")
f.mode
f.name
f.write(bytes("Write me to your leaders\n", 'UTF-8'))
f.close()
f = open("demofile.txt", "r+")
text = f.read
print(text)
f.close()
import os
os.remove("demofile.txt")
'''Creates a file called βCountries.txtβ. If one already exists then it will be overwritten with
a new blank file. It will add three lines of data to the file (the \n forces a new line after
each entry). It will then close the file, allowing the changes to the text file to be saved.'''
file = open("Countries.txt","w")
file.write("Italy\n")
file.write("Germany\n")
file.write("Spain\n")
file.close()
file = open(βCountries.txtβ,βrβ)
print(file.read())
'''This will open the Countries.txt file in βreadβ
mode and display the entire file.'''
file = open(βCountries.txtβ,βaβ)
file.write(βFrance\nβ)
file.close()
'''This will open the Countries.txt file in βappendβ
mode, add another line and then close the file.
If the file.close() line is not included, the
changes will not be saved to the text file.'''
```python
inputFile = open (βmyfile.txtβ, 'r')
outputFile = open (βmyoutputfile.txtβ, 'w')
msg = inputFile.read(10)
while len(msg):
outputFile.write(msg)
msg = inputFile.read(10)
inputFile.close()
outputFile.close()
def count_lines(file_name):
File = open(file_name)
count = 0
for line in File:
count = count + 1
return count
def head(file_name):
size = count_lines(file_name)
if size<20:
n_prints = size
else:
n_prints = 20
File = open(file_name)
counter = 0
for line in File
if counter > n_prints:
break
print(line)
counter += 1
return counter
fhand = open('mbox-short.txt')
for line in fhand:
line = line.rstrip()
# Skip 'uninteresting lines'
if not line.startswith('From:'):
continue
# Process our 'interesting' line
print(line)
fname = input('Enter the file name: ')
try:
fhand = open(fname)
except:
print('File cannot be opened:', fname)
exit()
close: Closes the file. Like File->Save... in your editor. β’ read: Reads the contents of the file. You can assign the result to a variable. β’ readline: Reads just one line of a text file. β’ truncate: Empties the file. Watch out if you care about the file. β’ write('stuff'): Writes βstuffβ to the file. β’ seek(0): Moves the read/write location to the beginning of the file.