2017-10-17 6 views
-2

Je veux enregistrer mon python dans un fichier json, mais le problème est que je dois nommer le nom de mon fichier json comme nom de titre.Enregistrer les noms de fichiers en tant que nom de la variable en Python

code:

data={ 
    "Title" : title.text, 
    "Registration": doctor.text, 
    "Keywords": list2, 
    "Article": list 
} 
#title.text="banana" 

with open('title.text.json', 'w',encoding='UTF-8') as f: 
    json.dump(data, f,ensure_ascii=False) 

Le résultat je m'y attendais: Enregistrer comme banana.json

Edit: Il fonctionne avec ce

with open('%s.json' % title_tag.text, 'w',encoding='UTF-8') as f: 
    json.dump(data, f,ensure_ascii=False) 
+0

Vous avez explicitement ouvert un fichier nommé 'data.json', puis vous lui avez écrit, pourquoi voudriez-vous qu'il écrit dans' banana.json'? – ShadowRanger

+1

Copie possible de [chaîne de variables d'insertion Python en tant que nom de fichier] (https://stackoverflow.com/questions/14622314/python-inserting-variable-string-as-file-name) – Unni

+0

@ShadowRanger suffit de l'éditer. – Makiyo

Répondre

1

vous pouvez utiliser le code suivant pour atteindre ce:

with open(title.text, 'w', encoding='UTF-8') as f: 
    json.dump(data, f, ensure_ascii=False) 
+0

Il va l'enregistrer en tant que fichier html au lieu de fichier json – Makiyo

+0

vous pouvez utiliser string.format pour formater votre chaîne .... '' 'avec open ('{file_name} .html'.format (nom_fichier = title.text), 'w', encoding = 'UTF-8') en tant que f''' En python3.6, vous pouvez le faire avec * avec open (f "{title.text} .html", 'w', encoding = 'UTF'8') comme f * – Ballack

+0

avec open ('% s.json'% titre_tag.text, 'w', encoding = 'UTF-8') comme f: json.dump (data, f, ensure_ascii = False) – Makiyo