IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Python Discussion :

Insertion d'une phrase au milieu d'un fichier


Sujet :

Python

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre averti
    Profil pro
    Étudiant
    Inscrit en
    Juillet 2007
    Messages
    21
    Détails du profil
    Informations personnelles :
    Localisation : France, Meurthe et Moselle (Lorraine)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Juillet 2007
    Messages : 21
    Par défaut Insertion d'une phrase au milieu d'un fichier
    Bonjour,

    je ne suis pas un expert Python et malgé mes recherches /tests je n'arrive pas a faire ce que je veux, à savoir modifier un fichier texte mais pas a la fin.

    Je voudrais le modifier en plein milieu. En utime recours il ya la copie mais je trouve ça relativement crade :s

    J'ai essayer de genre de choses :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    f=open('fichier.txt', 'a+')#seul moyen de pas tout écraser :s
    #localisation de l'endroit ou je veux modifier
    l='876'
    f.seek(l, 0)
    f.tell()
    f.write('une phrase en plein milieu')
    f.close()
    Mais le mode 'a' fait ce qu'il a à faire, ajouter....

    Au pire je peux lire ligne par ligne et balancer dans un autre fichier en modifiant au passage ce que je veux.... Mais a ce moment là Python propose-t-il des fonctions pour renommer / supprimer des fichiers ? (bon cette question je pense pouvoir trouver la réponse, mais si quelqu'un à déjà du faire ce que je cherche à faire, il a forcément une des deux solutions :p).

    Merci pour votre aide


    Edit : os.rename() pour la solution pas propre, la recherche fut courte

  2. #2
    Membre émérite
    Homme Profil pro
    heu...
    Inscrit en
    Octobre 2007
    Messages
    648
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Essonne (Île de France)

    Informations professionnelles :
    Activité : heu...

    Informations forums :
    Inscription : Octobre 2007
    Messages : 648
    Par défaut
    Hmmm, si ton but est de créer une copie modifiée d'un fichier texte, le mieux reste de stocker le contenu du fichier d'origine en mémoire, de le modifier et de le sauvegarder sous un autre nom :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    LimitSize=5000 #limit size in octet
     
    class ModList(object):
        def __init__(self):
            self.modList=[]
        def append(self,mode='i',line=1,char=1,text='',rtext=''):
        '''mode : 'i' (Insert) or 'r' (Replace)
          line : used in 'i' mode, indicate the number of line where the text should be inserted, begins to one.
          char : used in 'i' mode, indicate the index of the char where the text should be inserted, begins to zero.
          rtext : used in 'r' mode, indicate the text that should be replaced
          text : used in both modes, indicate the that will be inserted or will replace rtext.'''
            mod=()
            if mode=='i':
                mod+=(mode,line,char,text)
            if mode=='r':
                mod+=(mode,rtext,text)
            self.modList+=[mod]
        def verifyAndModify(self,num_line,line):
            for mod in self.modList:
                if mod[0]=='i' and num_line==mod[1]:
                    line=line[:mod[2]]+mod[3]+line[mod[2]:]
                if mod[0]=='r' and mod[1] in line:
                    line=line.replace(mod[1],mod[2])
            return line
     
     
    def copyModFile(modifList):
        if not isinstance(modifList,ModifList): raise Exception('modifList parameter must be a ModifListObject')
        f_in=open('./MyFile','r')
        f_out=open('./MyFile_New','w')
        copy=''
        copy_size=0
        line_count=0
        while 1:
            line=f_in.readline()
            line_count+=1
            count+=1
            if line:
                mod=modifList.verifyAndModify(line)
                copy+=mod
                copy_size+=len(mod)
                if copy_size>LimitSize:
                    f_out.write(copy)
                    copy=''
                    copy_size=0
            else :
                f_in.close()
                f_out.close()
                break
    Ce code devrait aller, bien sûr il est à adapter à ta situation, mais le concept est là, remarques il est un peu long cause, je pars du principe que ton fichier peut être volumineux, du coup faut pas surcharger la mémoire...

  3. #3
    Membre averti
    Profil pro
    Étudiant
    Inscrit en
    Juillet 2007
    Messages
    21
    Détails du profil
    Informations personnelles :
    Localisation : France, Meurthe et Moselle (Lorraine)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Juillet 2007
    Messages : 21
    Par défaut
    Bonjour,

    merci pour ta réponse. Je me penche sur ton code pour comprendre bien comment cela fonctionne. J'ai finalement fait la solution pas propre (lire ligne par ligne et modifier au passage avant de recopier dans un autre fichier), mais il est encore temps de changer.

    Désolé pour mon temps de réponse par contre, quelques soucis pour me log depuis le boulot

  4. #4
    Membre émérite
    Homme Profil pro
    heu...
    Inscrit en
    Octobre 2007
    Messages
    648
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Essonne (Île de France)

    Informations professionnelles :
    Activité : heu...

    Informations forums :
    Inscription : Octobre 2007
    Messages : 648
    Par défaut
    hmm, en relisant mon code, j'y ai vu quelque erreurs, et aucun exemple d'utilisation , ceci aidear à mieux comprendre :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    LimitSize=5000 #limit size in octet
     
    class ModList(object):
        '''It is an container for several modification which has to be performed on the text'''
        def __init__(self):
            self.modList=[]
        def append(self,mode='i',line=1,char=1,text='',rtext=''):
            '''mode : 'i' (Insert) or 'r' (Replace)
          line : used in 'i' mode, indicate the number of line where the text should be inserted, begins to one.
          char : used in 'i' mode, indicate the index of the char where the text should be inserted, begins to zero.
          rtext : used in 'r' mode, indicate the text that should be replaced
          text : used in both modes, indicate the that will be inserted or will replace rtext.'''
            mod=()
            if mode=='i':
                mod+=(mode,line,char,text)
            if mode=='r':
                mod+=(mode,rtext,text)
            self.modList+=[mod]
            self.modList.sort()
        def verifyAndModify(self,num_line,line):
            '''check if the num_line is in one of the modification, if yes modifies it, else no modification is done.
            the (un)modified line is returned'''
            lenOfMod=0
            for mod in self.modList:
                if mod[0]=='i' and num_line==mod[1]:
                    line=line[:mod[2]+lenOfMod]+mod[3]+line[mod[2]+lenOfMod:]
                    lenOfMod+=len(mod[3])
                if mod[0]=='r' and mod[1] in line:
                    line=line.replace(mod[1],mod[2])
            return line
     
     
    def copyModFile(modifList,f_inName,f_outName):
        if not isinstance(modifList,ModList): raise Exception('modifList parameter must be a ModifListObject')
        f_in=open(f_inName,'r')
        f_out=open(f_outName,'w')
        copy=''
        copy_size=0
        line_count=0
        while 1:
            line=f_in.readline()
            line_count+=1
            #count+=1
            if line:
                mod=modifList.verifyAndModify(line_count,line)
                print mod
                copy+=mod
                copy_size+=len(mod)
                if copy_size>LimitSize:
                    f_out.write(copy)
                    copy=''
                    copy_size=0
            else :
                if copy!='':
                    f_out.write(copy)
                f_in.close()
                f_out.close()
                break
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    #example of use:
    #the text of the file to read is :
    #"Yo ! I'm N.tox, and i'm a fool
    #but I'm harmless, don't worry about it ;p"
    Modifications=ModList()
    Modifications.append(mode='i',line=1,char=14,text=' a cool guy')
    Modifications.append(mode='r',rtext='N.tox',text='Minority')
    Modifications.append(mode='r',rtext='fool',text='nice guy')
    Modifications.append(mode='r',rtext='Yo',text='Hi')
    Modifications.append(mode='i',line=2,char=7,text=' not')
    Modifications.append(mode='r',rtext="don't",text='you better')
    copyModFile(Modifications,'D:/yo.txt','D:/yo_new.txt')
    #and the text of the new file is :
    #"Hi ! I'm Minority a cool guy, and i'm a nice guy
    #but I'm not harmless, you better worry about it ;p"

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Comment empêcher un passage à la ligne (au milieu d'une phrase) dans le code source ?
    Par martha20 dans le forum Balisage (X)HTML et validation W3C
    Réponses: 3
    Dernier message: 07/01/2011, 18h30
  2. modifier une ligne au milieu d'un fichier
    Par yoann38260 dans le forum Général Python
    Réponses: 5
    Dernier message: 20/11/2009, 17h58
  3. [DOM] [Xerces] Insertion d'une entité
    Par Traroth dans le forum Format d'échange (XML, JSON...)
    Réponses: 10
    Dernier message: 19/05/2008, 09h28
  4. Remplacer une donnée au milieu d'un fichier
    Par DindonSauvage dans le forum C++
    Réponses: 6
    Dernier message: 05/01/2007, 15h20
  5. Insert ds une column identity
    Par Trahwn dans le forum MS SQL Server
    Réponses: 11
    Dernier message: 06/10/2003, 15h14

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo