• PYTHON > les fichiers et dossiers

      TOUT SE FAIT AVEC LA BIBLIOTHÈQUE import os

      LES TESTS

      os.path.isabs(s)       # si un chemin est absolu
      os.path.isdir(s)       # si le chemin est un dossier
      os.pathisfile(path)   # si le chemin est un fichier régulier
      os.path.islink(path)   # si le chemin est un lien symbolique
      os.path.ismount(path)  # si le chemin est un point de montage

      CHEMIN ET DOSSIER COURANT

      Où suis-je ?

      os.getcwd()
      '/mon/dossier'

      Changer de dossier courant

      os.chdir('/chemin/dossier')

      LES DOSSIERS

      Vérifications

      Le dossier existe-t-il et est-ce un dossier ?

      os.path.isdir(path)

      Le dossier est-il vide ?

      Méthode 1

       

      if len(os.listdir('/home/varun/temp') ) == 0:
          print("dossier vide")

       

      Méthode 2

       

      if not os.listdir('/home/varun/temp'):
          print("dossier vide")

      LISTER LE CONTENU D’UN DOSSIER

      os.listdir()
      ['dossier', 'fichier1.txt', 'fichier2.txt', 'fichier.exe', 'toto']
      
      os.listdir('/chemin/dossier')
      ['fichier1.txt', 'fichier2.txt', 'monDossier']

      Créer un dossier

      os.mkdir('toto')

      Renommer

      os.rename('ancien',nouveau')

      Effacer Supprimer

      os.remove('fichier')
      os.rmdir('dossier') # ne supprime que les dossiers vides

       

      Pour supprimer un dossier avec tous les fichiers dedans :

       

      import shutil
      shutil.rmtree('dossier')

       

      VOIR AUSSI : https://docs.python.org/3/library/filesys.html

      LES FICHIERS

      OUVRIR UN FICHIER

      f = open('fichier', mode='r', encoding='utf-8') # open file in current directory 
      f = open('C:/mondossier/monfichier.txt') # specifying full path

       

      mode to read 'r', write 'w' or append 'a' to the file. We also specify if we want to open the file in text mode or binary mode.

      The default is reading in text mode. In this mode, we get strings when reading from the file.

      On the other hand, binary mode returns bytes and this is the mode to be used when dealing with non-text files like image or exe files.

       

      r Open a file for reading. (default)

      w Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists.

      x Open a file for exclusive creation. If the file already exists, the operation fails.

      a Open for appending at the end of the file without truncating it. Creates a new file if it does not exist.

      t Open in text mode. (default)

      b Open in binary mode (pour les images)

      + Open a file for updating (reading and writing)

       

      f = open("test.txt")      # equivalent to 'r' or 'rt'
      f = open("test.txt",'w')  # write in text mode
      f = open("img.bmp",'r+b') # read and write in binary mode

      FERMER UN FICHIER

      f.close()

       

      try:
          f = open("fichier")
          ... du code ...
      finally:
          f.close()

       

      with open("fichier", encoding='utf-8') as f:
          ... du code ...

      Écrire dans un fichier

      w écrasera le fichier, a ajoutera au fichier et x pour exclusif.

       

      with open('fichier.txt', 'w', encoding = 'utf-8') as f:
          f.write('ma première ligne\n')
          f.write('Ma deuxième ligne\n\n')

       

      \n pour sauter de ligne, sinon, le prochain insert se fera sur la même ligne.

      Ajouter à la fin d’un fichier

      En mode a ou ab : the write position is at the end of the file (an append). There are other permutations of the mode argument for updating (+), truncating (w) and binary (b) mode but starting with just "a" is your best. If you want to seek through the file to find the place where you should insert the line, use ‘r+’.

       

      with open("index.txt", "a") as myfile:
          myfile.write("text appended")

       

      a+ for Open for reading and writing. The file is created if it does not exist. The stream is positioned at the end of the file . The initial file position for reading is at the beginning of the file, but output is appended to the end of the file.

       

      with open("index.txt", "a+") as myfile:
          myfile.write("New text appended")

       

      How to append new data onto a new line?

       

      You can use "\n" while writing data to file.

       

      with open("index.txt", "a") as myfile:
          myfile.write("First Line\n")
          myfile.write("Second Line\n")

      LIRE UN FICHIER

      toutes les lignes

      with open('fichier') as f:
          data = f.read()
          ... du code ...

      ligne par ligne

      with open('fichier') as f:
          for line in f:
              print(line)

       

      readline() ne lit qu’une seule ligne. Si invoqué une nouvelle fois, la ligne suivante est affichée.

       

      f.readline()
      'ma première ligne\n'
      f.readline()
      'deuxième ligne\n'
      f.readline()
      'dernière ligne\n'
      f.readline()
      ''

       

      readlines() retourne un tableau de toutes les lignes.

       

      f.readlines()
      ['ma première ligne\n', 'deuxième ligne\n', 'dernière ligne\n']

      caractère par caractère

      f = open("fichier", 'r', encoding = 'utf-8')
      f.read(4) # les 4 premiers caractères
      abcd
      f.read(4) # puis les 4 autres suivants
      efgh
      f.read()  # le reste des caractères
      ijklmnopqrstuvwxyz
      f.read()  # la fin du fichier renvoie une chaine vide
      ''

       

      read() retourne un '\n'. Donc, à la fin du fichier, on se retrouve avec une ligne vide

       

      Pour se positionner à un endroit : seek(). Similarly, tell() returns our current position (in bytes).

       

      f.tell() # get the current file position
      56
      f.seek(0) # bring file cursor to initial position
      0
      print(f.read()) # read the entire file
      This is my first file
      This file
      contains three lines

      CHEMIN, NOM, EXTENSION

      import os
      nom, extension = os.path.splitext('/chemin/vers/fichier.ext')
      nom
      '/chemin/vers/fichier'
      extension
      '.ext'

      TOUTES LES MÉTHODES

      detach() Separate the underlying binary buffer from the TextIOBase and return it.

      fileno() renvoie un entier (file descriptor) du fichier.

      flush() Flush the write buffer of the file stream.

      isatty() Return True if the file stream is interactive.

      read(n) Read atmost n characters form the file. Reads till end of file if it is negative or None.

      readable() Returns True if the file stream can be read from.

      readline(n=-1) Read and return one line from the file. Reads in at most n bytes if specified.

      readlines(n=-1) Read and return a list of lines from the file. Reads in at most n bytes/characters if specified.

      seek(offset,from=SEEK_SET) Change the file position to offset bytes, in reference to from (start, current, end).

      seekable() Returns True if the file stream supports random access.

      tell() Returns the current file location.

      truncate(size=None) Resize the file stream to size bytes. If size is not specified, resize to current location.

      writable() Returns True if the file stream can be written to.

      write(s) Write string s to the file and return the number of characters written.

      writelines(lines) Write a list of lines to the file.

       

      voir :

      Python Program to Merge Mails

      Python Program to Find the Size (Resolution) of a Image

      Python Program to Find Hash of File

      Gestion des fichiers et des dossiers en python

      Manipuler les chemins

      abspath(path)         → Retourne un chemin absolu
      basename(p)           → Retourne le dernier élément d'un chemin
      commonprefix(list)    → Retourne le chemin commun le plus long d'une liste de chemins
      dirname(p)            → Retourne le dossier parent de l'élément
      getaTime(filename)    → date du dernier accès au fichier [os.stat()]
      getctime(filename)    → date du dernier changement de metadonnées du fichier
      getmTime(filename)    → date de la dernière modification du fichier
      getsize(filename)     → taille d'un fichier (en octets)
      join(path, s)         → Ajoute un élément au chemin passé en paramètre
      normcase(s)           → Normalise la casse d'un chemin
      normpath(path)        → Normalise le chemin, élimine les doubles barres obliques, etc.
      realpath(filename)    → Retourne le chemin canonique du nom de fichier spécifié (élimine les liens symboliques)
      samefile(f1, f2)      → Test si deux chemins font référence au même fichier réel
      sameopenfile(f1, f2)  → Test si deux objets de fichiers ouverts font référence au même fichier
      split(p)              → Fractionne un chemin d'accès. Retourne un tuple

       

      Quelques exemples d’utilisation:

      path = "/mon/chemin/vers/fichier.py"
      os.path.dirname(path)
      '/mon/chemin/vers'
      os.path.basename(path)
      'action.py'
      os.path.join(path, "func")
      '/mon/chemin/vers/fichier.py/func'
      os.path.split(path)
      ('/mon/chemin/vers', 'fichier.py')
      os.path.abspath(".")
      '/mon/chemin'

      Lister les fichiers d’un dossier

      os.listdir("/home/moi")
      ['.fichier_caché', 'dossier', 'fichier.txt']

      Lister les éléments récursivement

      dossier = "/chemin/dossier"
      for path, dirs, files in os.walk(dossier):
          for filename in files:
              print(filename)

      Recherche d’éléments par motif

      *  → n'importe quel séquence de caractères
      ?  → n'importe quel caractère
      [] → n'importe quel caractère listé entre les crochets

       

      import glob
      glob.glob(motif)  → Liste les dossiers et les fichiers correspondants au motif
      glob.iglob(motif) → Idem que glob mais retourne un itérateur
      glob.glob("/chemin/*.txt")
      ['/chemin/fichier.txt']

      Manipuler les éléments

      os.makedirs(path)   → Créer récursivement tous les dossiers d'un path si ceux-ci n'existent pas
      os.mkdir(path)      → Créer le dernier dossier d'un path. Si un des dossiers n'existe pas une erreur est retournée
      os.remove(path)     → Supprime le fichier / dossier indiqué
      os.rename(old, new) → Renomme le fichier / dossier indiqué

      REMPLACER DU TEXTE DANS UN FICHIER

      import fileinput
      for line in fileinput.input("test.txt", inplace=True):
          print "%d: %s" % (fileinput.filelineno(), line),

       

      Create a Text File

      f= open("guru99.txt","w+")

      We declared the variable f to open a file named textfile.txt. Open takes 2 arguments, the file that we want to open and a string that represents the kinds of permission or operation we want to do on the file

      Here we used "w" letter in our argument, which indicates write and the plus sign that means it will create a file if it does not exist in library

      The available option beside "w" are "r" for read and "a" for append and plus sign means if it is not there then create it

       

      for i in range(10):
           f.write("This is line %d\r\n" % (i+1))

      We have a for loop that runs over a range of 10 numbers.

      Using the write function to enter data into the file.

      The output we want to iterate in the file is "this is line number", which we declare with write function and then percent d (displays integer)

      So basically we are putting in the line number that we are writing, then putting it in a carriage return and a new line character


      f.close()

      This will close the instance of the file guru99.txt stored

      How to Append Data to a File

      You can also append a new text to the already existing file or the new file.

      Step 1)

      f=open("guru99.txt", "a+")

      Once again if you could see a plus sign in the code, it indicates that it will create a new file if it does not exist. But in our case we already have the file, so we are not required to create a new file.

      Step 2)

      for i in range(2):
           f.write("Appended line %d\r\n" % (i+1))

      This will write data into the file in append mode.

      Python FILE Tutorial: Create, Append, Read, Write

      You can see the output in "guru99.txt" file. The output of the code is that earlier file is appended with new data.

      Python FILE Tutorial: Create, Append, Read, Write

      How to Read a File

      1) Open the file in Read mode

      f=open("guru99.txt", "r")

       

      2) We use the mode function in the code to check that the file is in open mode. If yes, we proceed ahead

      if f.mode == 'r':

       

      3) Use f.read to read file data and store it in variable content

      contents =f.read()

       

      4) print contents

       

      Python FILE Tutorial: Create, Append, Read, Write

      How to Read a File line by line

      You can also read your .txt file line by line if your data is too big to read. This code will segregate your data in easy to ready mode

       

      Python FILE Tutorial: Create, Append, Read, Write

       

      When you run the code (f1=f.readlines()) for reading the file or document line by line, it will separate each line and present the file in a readable format. In our case the line is short and readable, the output will look similar to the read mode. But if there is a complex data file which is not readable, this piece of code could be useful.

      File Modes in Python

      r This is the default mode. It Opens file for reading.

      w This Mode Opens file for writing. If file does not exist, it creates a new file. If file exists it truncates the file.

      x Creates a new file. If file already exists, the operation fails.

      a Open file in append mode. If file does not exist, it creates a new file.

      t This is the default mode. It opens in text mode.

      b This opens in binary mode.

      + This will open a file for reading and writing (updating)

       

      Python 3 Example :

       

      def main():
          f= open("guru99.txt","w+")
          #f=open("guru99.txt","a+")
          for i in range(10):
               f.write("This is line %d\r\n" % (i+1))
          f.close()
          #Open the file back and read the contents
          #f=open("guru99.txt", "r")
          #if f.mode == 'r':
          #   contents =f.read()
          #    print (contents)
          #or, readlines reads the individual line into a list
          #fl =f.readlines()
          #for x in fl:
          #print(x)
      if __name__== "__main__":
        main()

       

      Résumé

      • Python allows you to read, write and delete files
      • Use the function open("filename","w+") to create a file. The + tells the python interpreter to open file with read and write permissions.
      • To append data to an existing file use the command open("Filename", "a")
      • Use the read function to read the ENTIRE contents of a file
      • Use the readlines function to read the content of the file one by one.

       

      COMPARER DEUX FICHIERS OU DOSSIERS

       

      File and Directory Comparisons

      see also the difflib module.

      The filecmp module defines the following functions:

      filecmp.cmp(f1, f2[, shallow]) Compare the files named f1 and f2, returning True if they seem equal, False otherwise. Unless shallow is given and is false, files with identical os.stat() signatures are taken to be equal. Files that were compared using this function will not be compared again unless their os.stat() signature changes. Note that no external programs are called from this function, giving it portability and efficiency.
      filecmp.cmpfiles(dir1, dir2, common[, shallow]) Compare the files in the two directories dir1 and dir2 whose names are given by common. Returns three lists of file names: match, mismatch, errors. match contains the list of files that match, mismatch contains the names of those that don’t, and errors lists the names of files which could not be compared. Files are listed in errors if they don’t exist in one of the directories, the user lacks permission to read them or if the comparison could not be done for some other reason. The shallow parameter has the same meaning and default value as for filecmp.cmp(). For example, cmpfiles('a', 'b', ['c', 'd/e']) will compare a/c with b/c and a/d/e with b/d/e. 'c' and 'd/e' will each be in one of the three returned lists.

      Example:

      >>> import filecmp
      >>> filecmp.cmp('undoc.rst', 'undoc.rst')
      True
      >>> filecmp.cmp('undoc.rst', 'index.rst')
      False

      dircmp

      dircmp instances are built using this constructor:

      class filecmp.dircmp(a, b[, ignore[, hide]])  Construct a new directory comparison object, to compare the directories a and b. ignore is a list of names to ignore, and defaults to ['RCS', 'CVS', 'tags']. hide is a list of names to hide, and defaults to [os.curdir, os.pardir].
      The dircmp class compares files by doing shallow comparisons as described for filecmp.cmp().
      The dircmp class provides the following methods:
      report() Print (to sys.stdout) a comparison between a and b.
      report_partial_closure() Print a comparison between a and b and common immediate subdirectories.
      report_full_closure() Print a comparison between a and b and common subdirectories (recursively).The dircmp class offers a number of interesting attributes that may be used to get various bits of information about the directory trees being compared.Note that via __getattr__() hooks, all attributes are computed lazily, so there is no speed penalty if only those attributes which are lightweight to compute are used.
      left The directory a.
      right The directory b.
      left_list Files and subdirectories in a, filtered by hide and ignore.
      right_list Files and subdirectories in b, filtered by hide and ignore.
      common Files and subdirectories in both a and b.
      left_onlyFiles and subdirectories only in a.
      right_onlyFiles and subdirectories only in b.
      common_dirsSubdirectories in both a and b.
      common_filesFiles in both a and b
      common_funnyNames in both a and b, such that the type differs between the directories, or names for which os.stat() reports an error.
      same_filesFiles which are identical in both a and b, using the class’s file comparison operator.
      diff_filesFiles which are in both a and b, whose contents differ according to the class’s file comparison operator.
      funny_filesFiles which are in both a and b, but could not be compared.
      subdirsA dictionary mapping names in common_dirs to dircmp objects.

      Here is a simplified example of using the subdirs attribute to search recursively through two directories to show common different files:

      from filecmp import dircmp
      def print_diff_files(dcmp):
          for name in dcmp.diff_files:
              print "diff_file %s found in %s and %s" % (name, dcmp.left, dcmp.right)
          for sub_dcmp in dcmp.subdirs.values():
              print_diff_files(sub_dcmp)
      
      dcmp = dircmp('dir1', 'dir2')
      print_diff_files(dcmp)

 

Aucun commentaire

 

Laissez un commentaire