F. Files - JulTob/Python GitHub Wiki

🐍 Open

  • 🐍 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.

🐢 Close

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()

✍ Write

file = open("ToDo.txt","w")
file.write("Jane\n")
file.write("Mery\n")
file.write("Chris Hemsworth\n")
file.close()

📜 Read

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)

📑 Append

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")

Modes

 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()

🐑 Count lines

def count_lines(file_name):
   File = open(file_name)
   count = 0
   for line in File:
      count = count + 1
   return count

🐙 Head

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

🦈 Filter


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)

🐿 Getter


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.