Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
-> Help: erreur print
#1
Hi everyone,
My project is to enter a json file or txt file. If it exists in my source then read the file entered and evaluate the condition.
This condition: Create a new dictionary from the list in the selected file with the condition if value 'numero' duplicated so return new dictionnary emty, otherwise create a new dictionary.

But my difficulty now is when I enter the file name to check, if true, instead of announcing the file content, I have to enter the file name again before announcing the next content. And if the 'numero' value is duplicated, a new dictionary is created.

This's my code and the information output.

import os
import json

#check file name in my source
def saisie_nomf(lst):
    print("Donner le nom du fichier avec l'extension ['.json','.txt']: ")
    correct = False
    file = input()
    while correct == False:
        if("." not in file):
            print("Le manque . de l'extension!")
            print("Donner le nom de fichier valide: ")
            file = input()
        else:
            if os.path.splitext(file)[1] in lst:
                if file not in l:
                    print("Fichier introuvable!")
                    print("Donner le nom de fichier valide: " )
                    file = input()

                else:
                    correct = True
            else:
                print("Extension incorrecte!")
                print("Donner le nom de fichier valide: ")
                file = input()

    return file

#check value 'numero': duplicated or not
def check(seq):
    for i in seq:
        (key, value), *rest = i.items()
        if value not in new_dict:
            new_dict[value] = dict(rest)
        else:
            return("Numero duplicated! " + "\n---->" +
                  value + "\nFichier non utilisable!")
    return new_dict

path = os.getcwd()
l = os.listdir(path)

new_dict = {}

print("Voici le contenu de dossier " + path + " - Recherche: \n" )
for file in l:
    print("- " + file + "\n")
list=['.json','.txt']
print("Voici le fichier choisi: " +saisie_nomf(list))


with open(saisie_nomf(list), 'r', encoding="utf-8") as liste:
    f = json.load(liste)

check(f)
print("Données source: ")
print(f)
Output:
Voici le contenu de dossier /Users/adelineng/PycharmProjects/TD5 - Recherche: - TD5_exo3.py - source1.json - TD5_exo2.py - source1bad3.json - test.py - source1bad2.json - source1.txt - source1bad1.json - TD5_exo1.py - .idea - TD5_exo4.py Donner le nom du fichier avec l'extension ['.json','.txt']: souce1b Le manque . de l'extension! Donner le nom de fichier valide: source1bad1.json Voici le fichier choisi: source1bad1.json #correct Donner le nom du fichier avec l'extension ['.json','.txt']: #I need enter one more time. source1bad1.json Données source: [{'numero': '21212121', 'name': 'Dupond', 'first': 'Alain', 'notes': [11, 9.5, 5.5, 18]}, {'numero': '21202120', 'name': 'Bru', 'first': 'Mélissa', 'notes': [11, 19.5, 15, 8]}, {'numero': '20212023', 'name': 'Bosse', 'first': 'Mélissa', 'notes': [13, 19.5, 15, 8]}, {'numero': '20212023', 'name': 'Bosse', 'first': 'Mélissa', 'notes': [13, 19.5, 15, 8]}] #value 'numero' duplicated 20212023 but it's not return a dict emty and the information numero duplicated like I want in my code. Dictionnaire extrait: 21212121 - Dupond , Alain , [11, 9.5, 5.5, 18] 21202120 - Bru , Mélissa , [11, 19.5, 15, 8] 20212023 - Bosse , Mélissa , [13, 19.5, 15, 8] None Vous souhaitez trier selon : 1 - Tri Numero ASC 2 - Tri Numero DESC 3 - Tri Nom 4 - Tri Prénom 5 - Tri Notes ASC 6 - Tri Notes DESC 7 - Tri Moy DESC 8 - Quitter Donner votre choix [1 - 8] :
Reply
#2
This calls your function that asks for all the input:

saisie_nomf(list)

Whenever you call this function you will have to type in a filename.

This calls your function twice:

saisie_nomf(list)
saisie_nomf(list)

Calling your function twice means you have to enter the file name twice. Why are you calling the function twice (once to print which file was chosen and once again to open the file)?
Reply
#3
(Apr-08-2020, 05:19 PM)deanhystad Wrote: This calls your function that asks for all the input:

saisie_nomf(list)

Whenever you call this function you will have to type in a filename.

This calls your function twice:

saisie_nomf(list)
saisie_nomf(list)

Calling your function twice means you have to enter the file name twice. Why are you calling the function twice (once to print which file was chosen and once again to open the file)?

I think like this: one time, I need return name file correct and one time I need return content file correct.
Reply
#4
No. You need to call the function once to get the filename. Then you can use the returned filename as many times as you want.

filename = saisie_nomf(list))
print("Voici le fichier choisi: "+filename)

with open(filename, 'r', encoding="utf-8") as liste:
Reply
#5
(Apr-08-2020, 07:51 PM)deanhystad Wrote: No. You need to call the function once to get the filename. Then you can use the returned filename as many times as you want.

filename = saisie_nomf(list))
print("Voici le fichier choisi: "+filename)

with open(filename, 'r', encoding="utf-8") as liste:

Thank you so much! I fixed. But how can I fix input like If the number is duplicated then the following contents are not notified
Now, I'm trying my code like this:

import os
import json

def saisie_nomf(lst):
    print("Donner le nom du fichier avec l'extension ['.json','.txt']: ")
    correct = False
    file = input()
    while correct == False:
        if("." not in file):
            print("Le manque . de l'extension!")
            print("Donner le nom de fichier valide: ")
            file = input()
        else:
            if os.path.splitext(file)[1] in lst:
                if file not in l:
                    print("Fichier introuvable!")
                    print("Donner le nom de fichier valide: " )
                    file = input()

                else:
                    correct = True
            else:
                print("Extension incorrecte!")
                print("Donner le nom de fichier valide: ")
                file = input()
    return file

def check(seq):
    for i in range(len(seq) - 1):
        for j in range(i + 1, len(seq)):
            if seq[i]['numero'] == seq[j]['numero']:
                print("Numero en double!\n " + "----> " + seq[i]['numero'] + " \n Fichier non utilisable!")
                return new_dict  # Return unaltered dictionary

        for i in seq:
            (key, value), *rest = i.items()
            new_dict[value] = dict(rest)

    return new_dict

def affichageE(etud_dico):
    for elem,elem2 in etud_dico.items():
        print(elem,"-", elem2['name'],",",elem2['first'],",",elem2['notes'])

....

path = os.getcwd()
l = os.listdir(path)

print("Voici le contenu de dossier " + path + " - Recherche: \n" )
for file in l:
    print("- " + file + "\n")
list=['.json','.txt']

nom_saisie_fichier = saisie_nomf(list)
print("Voici le fichier choisi: " +nom_saisie_fichier)

with open(nom_saisie_fichier, 'r', encoding="utf-8") as liste:
    f = json.load(liste)

new_dict = {}
check(f)

print("\nDictionnaire extrait: ")
for k in new_dict: print(affichageE(k))

ListeChoix =["","Tri Numero ASC","Tri Numero DESC","Tri Nom ","Tri Prénom","Tri Notes ASC","Tri Notes DESC","Tri Moy DESC", "Quitter"]
ch = menu(ListeChoix)

while ch != len(ListeChoix)-1 :
    if ch == 1:
        print(" Tri selon les numéros des étudiants croissantes : ")
        for e in sorted(new_dict):  print(e,"-", new_dict[e]['name'],",",new_dict[e]['first'],",",new_dict[e]['notes'])
    elif ch == 2:
        print(" Tri selon les numéros des étudiants décroissantes : ")
        for e in sorted(new_dict, reverse=True): print(e,"-", new_dict[e]['name'],",",new_dict[e]['first'],",",new_dict[e]['notes'])
    elif ch == 3 :
        print("  Tri selon les noms:")
        for k, v in sorted(new_dict.items(), key=lambda x: x[1]['name']): print(k, "-", v['name'], ",", v['first'], ",", v['notes'])
    elif ch == 4 :
        print("  Tri selon les prénoms:")
        for k, v in sorted(new_dict.items(), key=lambda x: x[1]['first']): print(k, "-", v['name'], ",", v['first'], ",", v['notes'])
    elif ch == 5 :
        print("  Tri selon les notes croissantes :")
        for k, v in sorted(new_dict.items(), key=lambda x: x[1]['notes']): print(k, "-", v['name'], ",", v['first'], ",", v['notes'])
    elif ch == 6 :
        print("  Tri selon les notes décroissantes :")
        for k, v in sorted(new_dict.items(), key=lambda x: x[1]['notes'], reverse=True): print(k, "-", v['name'], ",", v['first'], ",", v['notes'])
    elif ch == 7 :
        print("  Tri selon la moyenne décroissante :")
        for k, v in sorted(new_dict.items(), key=lambda x: moyenne(x[1]['notes']), reverse=True):
            print(k, "-", v['name'], ",", v['first'], ",", v['notes'], "-", moyenne(v['notes']))
    ch = menu(ListeChoix)
Output:
Donner le nom du fichier avec l'extension ['.json','.txt']: source1bad1.json Voici le fichier choisi: source1bad1.json Numero en double! ----> 20212023 Fichier non utilisable! Dictionnaire extrait: Traceback (most recent call last): File "/Users/adelineng/PycharmProjects/TD5/TD5_exo4.py", line 95, in <module> for k in new_dict: print(affichageE(k)) File "/Users/adelineng/PycharmProjects/TD5/TD5_exo4.py", line 44, in affichageE for elem,elem2 in etud_dico.items(): AttributeError: 'str' object has no attribute 'items'
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Erreur de code python sur un template rpm de zabbix samba 0 1,898 Apr-02-2021, 09:43 AM
Last Post: samba
  Erreur Code access violation reading 0x00000004 yan_mhb 0 2,292 Jul-10-2020, 02:28 PM
Last Post: yan_mhb
  Erreur Code yan_mhb 2 2,066 Jul-09-2020, 03:50 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020