Writing in another file in python leaves my file empty - python

def enr_score(nom_jouer, n, con):
score = open('Score.txt', 'a')
seconds = time.time()
local_time = time.ctime(seconds)
score.write("Temp de registration: ")
score.write(local_time)
score.write("JOUER: ")
score.write(nom_jouer)
score.write("\n")
score.write("Il/Elle a fini le jeu avec - ")
score.write(n)
score.write(" - disques apres - ")
score.write(con)
score.write(" - tentatives.")
score.write("\n")
score.close()
return "Ton score a ete enregistre!"
I got this code but for some reason when I check the Score.txt file it's empty. Shouldn't something be written in it?
There's no errors btw
This is the code that calls the function btw
nom_jouer = input("\nComment vous appelez vous? \n \nUSERNAME: ") #demande le nom de jouer
from Partie_E import enr_score
nr_disq = str(n)
tent = str(con)
enr_score(nom_jouer, nr_disq, tent)

Ok. So, basically I was a bit dumb (I'm relatively new to programming) and didn't realize I was editing another file than the one I was looking at.
It created the file in an outside folder and I thought it would edit the already existing one in the same folder as the .py files.
Sorry for the mind-F.

Related

Problem with cryptography.fernet: decrypt my code with a wrong key

I was working with fernet to encrypt. In the tests I founded that if I change the last character of the key, fernet it is able to dencrypt.
For example if the key is ZwvCXUGvnG0RvkhNszIQsQOqz8yaKjUSJpxraDVsxd4= and i type ZwvCXUGvnG0RvkhNszIQsQOqz8yaKjUSJpxraDVsxd5= instead, the program dencrypt my code. I founded this error bc i was lazy to copy a whole new key, so i decided to only change the last character. This happen with every consecuent character in the last one character of the key.
If anyone could help me i would be very thankfull
This is my code
from cryptography.fernet import Fernet
text1="""Find me and follow me through corridors, refectories and files
You must follow, leave this academic factory
You'll find me in the matinée, the dark of the matinée
It's better in the matinée, the dark of the matinée is mine
Yes, it's mine"""
def crearLLave():
key=Fernet.generate_key()
print(key.decode())
return Fernet(key)
def crearLLaveManual(llave):
try:
return Fernet(llave)
except:
again=bytes(input("Formato incorrecto "), "ascii")
return crearLLaveManual(again)
def encriptarTexto(cadena, llave):
return llave.encrypt(str.encode(cadena))
def desencriptarTexto(cadena_encriptada, llave):
try:
return llave.decrypt(cadena_encriptada).decode()
except:
cadena=bytes(input("La cámara de los secretos no se abrirá, intente de nuevo: "),"ascii")
return desencriptarTexto(cadena_encriptada, crearLLaveManual(cadena))
llave=crearLLave()
texto_encriptado=encriptarTexto(text1, llave)
print("La cadena encriptada es: ",texto_encriptado.decode())
cadenaLlave=bytes(input("Escriba la llave para desencriptar el texto: "), "ascii")
llaveManual=crearLLaveManual(cadenaLlave)
print("El texto desencriptado es: ",desencriptarTexto(texto_encriptado, llaveManual))
Console Message:
lIX2AfP-cyFRNgYgFRf3Sy3uKQ4Hrr4Lvrn12wFGo30=
La cadena encriptada es: gAAAAABjg7kdWTCIRjIrIAFk2fQg-znc1zRdrc7VaTkjcKZL1RZ2jmCjvf6NlzQ-39yxh0BMXY0FkrBTN0Ky51HiGy9cxmlbpZ7_Jwp6wml2DsMkCWf7h49EYLN8hjtpzFoiTUy7coguSXgFDBVVyucAUhgcn1EzleHJ_pKlDsyw6EnNLVBqUkmI8WYOY5NwEfCKx3UUlvV3dYDZqjeVqMX90CaAueUMtgDvcVP77tkngK7U2jfneH85bxBo8LJooenFnVeqNxwc70a8vY-GmOihnbDyAOT-GYwmLMssMP5QYDWNBnnTEmMSm4Dt-OHCvOYRyie82T6Art6PK5miinVsjsvkXpd6g343tmNSg34XMbMqgTIILXB7t6gZqdfnpUNUJ6vLfQvM4s4bYSltEEgTSIwrMUUUbA==
Escriba la llave para desencriptar el texto: lIX2AfP-cyFRNgYgFRf3Sy3uKQ4Hrr4Lvrn12wFGo31=
El texto desencriptado es: Find me and follow me through corridors, refectories and files
You must follow, leave this academic factory
You'll find me in the matinée, the dark of the matinée
It's better in the matinée, the dark of the matinée is mine
Yes, it's mine

How to import a whole Jupyter NB file in another Jupyter NB?

I'm new on this area and I've stared to learn Python 3 on a Brazilian platform for coding education.
The thing is:
I have two programs, one is a "main game" and the other is some "menu selector" for any number of programs I would like to import. The course's teacher is using Pycharm and I'm using Jupyter Notebook to follow the scheddule, so now I'm facing an issue on trying to import and simply nothing happening.
I've searched some forums, Stackoverflow included, and couldn't resolve this.
The main game (adivinhacao.ipynb) is:
import random
aleatorio = random.randrange(1,101)
tentativas = 0
rodada = 1
pontos = 1000
print(aleatorio)
# Para selecionar o nível de dificuldade do jogo
print("Escolha o nível de dificuldade")
print("(1) Fácil, (2) Médio, (3) Difícil")
nivel = int(input("Digite o nível: "))
if(nivel == 1):
tentativas = 10
elif(nivel == 2):
tentativas = 5
else:
tentativas = 3
#(more code)
And the selector (jogos.ipynb), which is not importing anything, is:
!pip install import-ipynb
import import_ipynb
import adivinhacao
It worked once (displayed everything I've wrote on adivinhacao.ipynb) and after I've changed one commentary, no more. Can someone help me?
Try this
%run adivinhacao.ipynb

TypeError: 'str' object is not callable -what have i done wrong?

im not sure - i searched over an hour how to solve it. I rewrite the code 4 times but it still wont work - at all, its a realy simple code but i dont know how the failure has happen.
Code:
pin = '4372'
konto = '5000'
pin_s = False
kontostand = False
while pin_s == False:
pin_e = input ("Bitte geben Sie ihren Pin ein: ")
if pin == pin_e:
pin_s = True
else:
pin_s = False
print ("Ihr Kontostand beträgt: ", konto)
while kontostand == False:
geld_a = input("Bitte geben sie den Betrag ein den sie abheben möchten: ")
if geld_a > konto:
print("Ihr Kontostand reicht nicht aus. Er beträgt: ", konto,"€")
print("Bitte wählen sie einen anderen Betrag.")
else:
kontostand = True
print ("Sie heben ", geld_a ("€ ab"))
print ("Ihr neuer Kontostand beträgt: "), konto - geld_a ("€")
The Error happens in line 23
I totally cant see what i have made wrong, especially its really simple. i started with c++ but for my university i have to start with python now.
So... can someone eventually tell me where is the failure? :(
You're using your parentheses wrong. It appears you want to append one string to another for printing, but instead it's being interpreted as a function call. Use commas instead:
print ("Sie heben ", geld_a, "€ ab")
Google translate helped with the context a bit. I think what you are trying to do is something like this:
print("Sie heben {} (€ ab)".format(geld_a))
or
print("Sie heben " + str(geld_a) + "(€ ab)")
As others have said parenthesis () denote a method call but a string is not a method.

Python "Hello World" for Libreoffice-calc and Openoffice-calc [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
There is a python-helloworld example for Libre/Openoffice-writer (which is included in Libreoffice 4.1.6.2:
def HelloWorldWriter( ):
"""Prints the string 'Hello World(in Python)' into the current document"""
#get the doc from the scripting context which is made available to all scripts
desktop = XSCRIPTCONTEXT.getDesktop()
model = desktop.getCurrentComponent()
#check whether there's already an opened document. Otherwise, create a new one
if not hasattr(model, "Text"):
model = desktop.loadComponentFromURL(
"private:factory/swriter","_blank", 0, () )
#get the XText interface
text = model.Text
#create an XTextRange at the end of the document
tRange = text.End
#and set the string
tRange.String = "Hello World (in Python)"
return None
That script checks for an open writer document, creates a new one if one does not exist and outputs a string into that document.
Is there something similar for Libreoffice/Openoffice-calc?
Ideally, it should include:
· Read a table cell
· Write a table cell
· Save as ODT/XLS/CSV
For open office check it :
http://stuvel.eu/ooo-python : http://www.apidev.fr/blog/2011/07/18/utiliser-openoffice-avec-python/ the explanation is in french but check the code :
import os, sys
if sys.platform == 'win32':
#This is required in order to make pyuno usable with the default python interpreter under windows
#Some environment varaible must be modified
#get the install path from registry
import _winreg
value = _winreg.QueryValue(_winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\OpenOffice.org\UNO\InstallPath')
install_folder = '\\'.join(value.split('\\')[:-1])
#modify the environment variables
os.environ['URE_BOOTSTRAP'] = 'vnd.sun.star.pathname:{0}\\program\\fundamental.ini'.format(install_folder)
os.environ['UNO_PATH'] = install_folder+'\\program\\'
sys.path.append(install_folder+'\\Basis\\program')
paths = ''
for path in ("\\URE\\bin;", "\\Basis\\program;"):
paths += install_folder + path
os.environ['PATH'] = paths+ os.environ['PATH']
import uno
using the calc :
class UnoClient:
def __init__(self):
localContext = uno.getComponentContext()
resolver = localContext.ServiceManager.createInstanceWithContext(
"com.sun.star.bridge.UnoUrlResolver", localContext)
self.smgr = resolver.resolve("uno:socket,host=localhost,port=2002;urp;StarOffice.ServiceManager")
def create_document(self, app):
remoteContext = self.smgr.getPropertyValue("DefaultContext")
desktop = self.smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",remoteContext)
url = "private:factory/{0}".format(app)
return desktop.loadComponentFromURL(url,"_blank", 0, () )
you should use it like that :
calc = UnoClient().create_document('scalc') #cree un nouveau classeur
sheet = calc.getSheets().getByIndex(0) #1ere feuille du classeur
sheet.getCellByPosition(0, 0).setString("Salut") #Un texte
sheet.getCellByPosition(0, 1).setValue(3.14) #Un nombre
sheet.getCellByPosition(0, 2).setFormula("=SUM(2+2)") #Une formule
sheet.getCellByPosition(0, 2).CellBackColor = int("ff7f00", 16) #Couleur RGB de fond
sheet.getCellByPosition(0, 2).CharUnderline = 1 # Souligne
sheet.getCellByPosition(0, 2).CharHeight = 16 #Taille de la police
sheet.getCellByPosition(0, 2).CharWeight = 150 #Gras
sheet.getCellByPosition(0, 2).CharPosture = 2 #Italique
And check it ! http://oosheet.hacklab.com.br/

updating tkinter window (Python 3.4)

Good Afternoon all,
I've been working on a contact-book program for a school project. I've got all of the underlying code complete. However I've decided to take it one step further and implement a basic interface. I am trying to display all of the contacts using the code snippet below:
elif x==2:
phonebook_data= open(data_path,mode='r',encoding = 'utf8')
if os.stat(data_path)[6]==0:
print("Your contact book is empty.")
else:
for line in phonebook_data:
data= eval(line)
for k,v in sorted(data.items()):
x= (k + ": " + v)
from tkinter import *
root = Tk()
root.title("Contacts")
text = Text(root)
text.insert('1.0', x)
text.pack()
text.update()
root.mainloop()
phonebook_data.close()
The program works, however every contact opens in a new window. I would like to display all of the same information in a single loop. I'm fairly new to tkinter and I apologize if the code is confusing at all. Any help would be greatly appreciated!!
First of all, the top of the snippet could be much more efficient:
phonebook_data= open(data_path,mode='r',encoding = 'utf8') should be changed to
phonebook_data = open(data_path).
Afterwards, just use:
contents = phonebook_data.read()
if contents == "": # Can be shortened to `if not contents:`
print("Your contact book is empty.")
And by the way, it's good practice to close the file as soon as you're done using it.
phonebook_data = open(data_path)
contents = phonebook_data.read()
phonebook_data.close()
if contents == "":
print("Your contact book is empty.")
Now for your graphics issue. Firstly, you should consider whether or not you really need a graphical interface for this application. If so:
# Assuming that the contact book is formatted `Name` `Number` (split by a space)
name_number = []
for line in contents.split("\n"): # Get each line
name, number = line.split()
name_number.append(name + ": " + number) # Append a string of `Name`: `Number` to the list
name_number.sort() # Sort by name
root = Tk()
root.title("Contact Book")
text = Text(root)
text.pack(fill=BOTH)
text.insert("\n".join(name_number))
root.mainloop()
Considering how much I have shown you, it would probably be considered cheating for you to use it. Do some more research into the code though, it didn't seem like the algorithm would work in the first place.

Categories