Contenu | Rechercher | Menus

Annonce

Si vous avez des soucis pour rester connecté, déconnectez-vous puis reconnectez-vous depuis ce lien en cochant la case
Me connecter automatiquement lors de mes prochaines visites.

À propos de l'équipe du forum.

#51 Le 22/11/2018, à 12:29

pingouinux

Re : Lecture fichier Csv

On peut aussi y arriver en n'utilisant qu'une seule variable de cumul.

................................
    for row in reader:
................................
            cumul.append(["HOST","APPLY", '-'.join((typ[suffix],row0))])
            cumul.append(["HC","ADDMEMBER", '-'.join((typ[suffix],row0))])
    for ligne in cumul[0::2]: writer.writerow(ligne)
    for ligne in cumul[1::2]: writer.writerow(ligne)

Hors ligne

#52 Le 22/11/2018, à 15:52

sylpard

Re : Lecture fichier Csv

à la ligne

writer.writerow(["HC","MEMBERS2", '-'.join((typ[suffix],row0)), row0, row[1].replace("'", "")])

comment pourrais faire pour afficher dans le fichier csv crée la ligne de type suivant :

HC;ADDMEMBER2;All-hosts;Bdd-pdaccteldb01|nas-pdaccteldn01|Tomc-pdacctelas01|Ap-pdacctelht01|Tomc-pdacctelas02|Ap-pdacctelht02|Tomc-pdacctelas03|Tomc-pdacctelas03

All-hosts est ecrit en dur mais le reste a déjà été récupéré mais je ne sais pas comment l' écrire sur une ligne


import sys
import csv
import glob
import os
import re

typ={'las':'Tomc', 'lht':'Ap', 'ldb':'Bdd','ldn':'nas'}
repertoire='export'
fic=glob.glob('*.csv')[0]
cumul=[]
cumul1=[]
cumul2=[]
cumul3=[]
with open(fic) as csvFile, open(os.path.join(repertoire,"result.csv"), "w") as resultfile:
    racine=repr(csvFile).split("'")[1].replace('.csv','')
    reader = csv.reader(csvFile)
    writer = csv.writer(resultfile, lineterminator = "\n", delimiter=";")
    writer.writerow(["HG","ADD", racine])
    boucle = 0
    for row in reader:
        boucle += 1
        if boucle > 2:
            row0=row[0].strip("'")
            suffix=re.sub('\d+$','',row0)[-3:]
            writer.writerow(["HOST","ADD", '-'.join((typ[suffix],row0)), row0, row[1].replace("'", "")])
            cumul.append(["HOST","APPLY", '-'.join((typ[suffix],row0))])
            cumul1.append(["HC","ADDMEMBER",'-'.join((typ[suffix],row0))])
            cumul2.append(["ACLRESOURCE","GRANT_HOSTGROUP",'-'.join((typ[suffix],row0))])
            cumul3.append(["HOST","SETPARAM",'-'.join((typ[suffix],row0))])
    for ligne in cumul: writer.writerow(ligne)
    writer.writerow(["HC","MEMBERS2", "All-hosts",'-'.join((typ[suffix],row0)), row0, row[1].replace("'", "")])
    for ligne in cumul1: writer.writerow(ligne)
    for ligne in cumul2: writer.writerow(ligne)
    for ligne in cumul3: writer.writerow(ligne)
csvFile.close()

Hors ligne

#53 Le 22/11/2018, à 20:13

pingouinux

Re : Lecture fichier Csv

Là, je n'arrive plus à suivre…
Il faudrait que tu fournisses un fichier de données, et un fichier résultat tel que tu le souhaites.

Hors ligne

#54 Le 24/11/2018, à 08:16

pingouinux

Re : Lecture fichier Csv

Peut-être ceci ?

import sys
import csv
import glob
import os
import re

typ={'las':'Tomc', 'lht':'Ap', 'ldb':'Bdd','ldn':'nas'}
repertoire='export'
fic=glob.glob('*.csv')[0]
cumul=[]
cumul1=[]
cumul2=[]
cumul3=[]
cumul_all=[]
with open(fic) as csvFile, open(os.path.join(repertoire,"result.csv"), "w") as resultfile:
    racine=repr(csvFile).split("'")[1].replace('.csv','')
    reader = csv.reader(csvFile)
    writer = csv.writer(resultfile, lineterminator = "\n", delimiter=";")
    writer.writerow(["HG","ADD", racine])
    boucle = 0
    for row in reader:
        boucle += 1
        if boucle > 2:
            row0=row[0].strip("'")
            row1=row[1].strip("'")
            suffix=re.sub('\d+$','',row0)[-3:]
            suff_row0='-'.join((typ[suffix],row0))
            writer.writerow(["HOST","ADD", suff_row0, row0, row1])
            cumul.append(["HOST","APPLY", suff_row0])
            cumul1.append(["HC","ADDMEMBER",suff_row0])
            cumul2.append(["ACLRESOURCE","GRANT_HOSTGROUP",suff_row0])
            cumul3.append(["HOST","SETPARAM",suff_row0])
            cumul_all.append(suff_row0)
    for ligne in cumul: writer.writerow(ligne)
    writer.writerow(["HC","MEMBERS2", "All-hosts",'|'.join(cumul_all)])
    for ligne in cumul1: writer.writerow(ligne)
    for ligne in cumul2: writer.writerow(ligne)
    for ligne in cumul3: writer.writerow(ligne)
csvFile.close()

Dernière modification par pingouinux (Le 24/11/2018, à 10:43)

Hors ligne

#55 Le 26/11/2018, à 09:17

sylpard

Re : Lecture fichier Csv

niquel c'est exactement cela !!!!

Merci beaucoup !!

Hors ligne

#56 Le 26/11/2018, à 09:24

pingouinux

Re : Lecture fichier Csv

Ceci devrait être équivalent, en n'utilisant qu'une seule variable de cumul.

import csv
import glob
import os
import re

typ={'las':'Tomc', 'lht':'Ap', 'ldb':'Bdd','ldn':'nas'}
repertoire='export'
fic=glob.glob('*.csv')[0]
cumul=[]
with open(fic) as csvFile, open(os.path.join(repertoire,"result.csv"), "w") as resultfile:
    racine=repr(csvFile).split("'")[1].replace('.csv','')
    reader = csv.reader(csvFile)
    writer = csv.writer(resultfile, lineterminator = "\n", delimiter=";")
    writer.writerow(["HG","ADD", racine])
    boucle = 0
    for row in reader:
        boucle += 1
        if boucle > 2:
            row0=row[0].strip("'")
            row1=row[1].strip("'")
            suffix=re.sub('\d+$','',row0)[-3:]
            suff_row0='-'.join((typ[suffix],row0))
            writer.writerow(["HOST","ADD", suff_row0, row0, row1])
            cumul.append(suff_row0)
    for ligne in cumul: writer.writerow(["HOST","APPLY"]+[ligne])
    writer.writerow(["HC","MEMBERS2", "All-hosts",'|'.join(cumul)])
    for ligne in cumul: writer.writerow(["HC","ADDMEMBER"]+[ligne])
    for ligne in cumul: writer.writerow(["ACLRESOURCE","GRANT_HOSTGROUP"]+[ligne])
    for ligne in cumul: writer.writerow(["HOST","SETPARAM"]+[ligne])
csvFile.close()

Hors ligne

#57 Le 30/11/2018, à 10:02

sylpard

Re : Lecture fichier Csv

en complément du script ci-dessous j aurais besoin qu' au niveau de la ligne

writer.writerow(["HG","ADD", racine])

soit ajouté les variables "envir" et "zone"  sous cette forme :

HG;ADD;ACCTE_qfzh

l' idée est de lire le fichier et si le nom de la machine est qfaccteldb01 ou claccteldb01 alors la ligne ci-dessus sera

HG;ADD;ACCTE_qfzh ouHG;ADD;ACCTE_clzh

suis je clair ? j' en doute ....



import sys
import csv
import glob
import os
import re

typ={'las':'Tomc', 'lht':'Ap', 'ldb':'Bdd','ldn':'nas'}
envir={'qf':'qf', 'dv':'dv', 'cl':'cl'}
zone={'dv':'zh', 'qf':'zh'}
repertoire='export'
fic=glob.glob('*.csv')[0]
cumul=[]
cumul1=[]
cumul2=[]
cumul3=[]
cumul_all=[]
with open(fic) as csvFile, open(os.path.join(repertoire,"result.csv"), "w") as resultfile:
    racine=repr(csvFile).split("'")[1].replace('.csv','')
    reader = csv.reader(csvFile)
    writer = csv.writer(resultfile, lineterminator = "\n", delimiter=";")
    writer.writerow(["HG","ADD", racine])
    boucle = 0
    for row in reader:
        boucle += 1
        if boucle > 2:
            row0=row[0].strip("'")
            row1=row[1].strip("'")
            suffix=re.sub('\d+$','',row0)[-3:]
            suff_row0='-'.join((typ[suffix],row0))
            writer.writerow(["HOST","ADD", suff_row0, row0, row1])
            cumul.append(["HOST","APPLY", suff_row0])
            cumul1.append(["HC","ADDMEMBER",suff_row0])
            cumul2.append(["ACLRESOURCE","GRANT_HOSTGROUP",suff_row0])
            cumul3.append(["HOST","SETPARAM",suff_row0])
            cumul_all.append(suff_row0)
    for ligne in cumul: writer.writerow(ligne)
    writer.writerow(["HC","MEMBERS2", "All-hosts",'|'.join(cumul_all)])
    for ligne in cumul1: writer.writerow(ligne)
    for ligne in cumul2: writer.writerow(ligne)
    for ligne in cumul3: writer.writerow(ligne)
csvFile.close()

Hors ligne

#58 Le 30/11/2018, à 10:21

pingouinux

Re : Lecture fichier Csv

Il faut que tu ajoutes l'information à racine.
envir et zone ne me semblent pas définis correctement. Chaque clé dans ces dictionnaires devrait être une information connue.

Hors ligne

#59 Le 30/11/2018, à 11:41

sylpard

Re : Lecture fichier Csv

pingouinux a écrit :

Chaque clé dans ces dictionnaires devrait être une information connue

euhhh oui ???

j'ai bien suivi ce que tu as fait

typ={'las':'Tomc', 'lht':'Ap', 'ldb':'Bdd','ldn':'nas'}

mais je ne vois pas comment intégrer l'ensemble

Dernière modification par sylpard (Le 30/11/2018, à 11:59)

Hors ligne

#60 Le 30/11/2018, à 12:08

pingouinux

Re : Lecture fichier Csv

typ={'las':'Tomc', 'lht':'Ap', 'ldb':'Bdd','ldn':'nas'}

Par exemple, avec ce dictionnaire, les clés sont 'las', 'lht', 'ldb', 'ldn', et ce sont les suffixes récupérés sur chaque ligne du fichier.
Les valeurs sont 'Tomc', 'Ap', 'Bdd', 'nas'.
typ['las'] contient la valeur 'Tomc'.

De plus

................
    writer.writerow(["HG","ADD", racine])   # Ici, avant la boucle, tu ne connais pas le nom des machines
    boucle = 0
    for row in reader:
        boucle += 1   # Tu ne vas lire le nom des machines qu'ici, dans la boucle
................

Hors ligne

#61 Le 30/11/2018, à 14:45

sylpard

Re : Lecture fichier Csv

tu peux m' expliquer cette partie stp ?

row0=row[0].strip("'")
            row1=row[1].strip("'")
            suffix=re.sub('\d+$','',row0)[-3:]
            suff_row0='-'.join((typ[suffix],row0))

Dernière modification par sylpard (Le 30/11/2018, à 15:22)

Hors ligne

#62 Le 30/11/2018, à 17:04

pingouinux

Re : Lecture fichier Csv

@sylpard #61 :
1)

row0=row[0].strip("'")

Supprime les ' au début et à la fin de la chaîne.

pydoc3 str.strip a écrit :

str.strip = strip(...)
    S.strip([chars]) -> str
   
    Return a copy of the string S with leading and trailing
    whitespace removed.
    If chars is given and not None, remove characters in chars instead.

2)

suffix=re.sub('\d+$','',row0)

Suppression des chiffres décimaux en fin de chaîne.

pydoc3 re.sub a écrit :

re.sub = sub(pattern, repl, string, count=0, flags=0)
    Return the string obtained by replacing the leftmost
    non-overlapping occurrences of the pattern in string by the
    replacement repl.  repl can be either a string or a callable;
    if a string, backslash escapes in it are processed.  If it is
    a callable, it's passed the match object and must return
    a replacement string to be used.

3)

suffix=re.sub('\d+$','',row0)[-3:]

Comme la commande précédente, mais on ne garde que les 3 derniers caractères.
4)

suff_row0='-'.join((typ[suffix],row0))

On concatène les chaînes typ[suffix] et row0 en utilsant - comme séparateur.

pydoc3 str.join a écrit :

str.join = join(...)
    S.join(iterable) -> str
   
    Return a string which is the concatenation of the strings in the
    iterable.  The separator between elements is S.

Hors ligne

#63 Le 04/12/2018, à 10:33

sylpard

Re : Lecture fichier Csv

Merci de tes explications ! wink

Hors ligne

#64 Le 07/12/2018, à 09:37

sylpard

Re : Lecture fichier Csv

Bonjour,

j' ai des adresses ip du type 10.143.xx.xx ou 10.43.xx.xx.  et j'aimerais ne selectionner le 4 éme octet et le placer dans une variable , pourriez vous me guider dans la commande à utiliser ?

Merci

Hors ligne