Python: Error in function [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
So I have a function called LoopingSpace. It takes no parameter
def loopingSpace():
for i in range (3):
print ""
i +=1
Whenever, it's called. It will print three blank lines.
For example; if I type
def loopingSpace():
for i in range (3):
print ""
i +=1
print"Hi"
loopingSpace()
print"Hi"
It will nicely output
Hi
Hi # As you can see three blanks.
However, when you put this function in a huge syntax like.
from random import randint
#Variabel
#--------------------------------------------------------------------
playername=[]
#Player disini mencatat skor. Jumlah Uang/Nilai Saham/Total harta/Health
playerOne=[0,0,0,0]
playerTwo=[0,0,0,0]
playerThree=[0,0,0,0]
#Stok disini mencatat banyak saham yang dimiliki peserta. A/B/C/D/E/F/G/H
stockOne=[0,0,0,0,0,0,0,0]
stockTwo=[0,0,0,0,0,0,0,0]
stockThree=[0,0,0,0,0,0,0,0]
#Tool disini mencatat apabila peserta memiliki barang. Diamond/Buy/Sell/Diamond/Poison
toolOne=[0,0,0,0,0]
toolTwo=[0,0,0,0,0]
toolThree=[0,0,0,0,0]
#Price disini mencatat harga saham. A/B/C/D/E/F/G/H
price=[0,0,0,0,0,0,0,0]
#clockTracker. Day dan turn counter
clockTracker=[0,0]
hari=["Senin","Selasa","Rabu","Kamis","Jumat","Sabtu","Minggu"]
listing=[playerOne,playerTwo,playerThree]
toolListing=[toolOne,toolTwo,toolThree]
#Nama saham
stockName=["Alama Inc.","Bwah! Bwah! Bwah! LCD","CUIT! CUIT CV","Dong Inc.","Eeeeeeeeeeeeah!","Foo il company.","Gogogogo Ind.","Halllo."
#--------------------------------------------------------------------
# THIS IS THE CODE. THIS IS THE CODE. THIS IS THE CODE
def loopingSpace():
for i in range (3):
print ""
i +=1
#
def startingTheGame():
loopingSpace()
print "Selamat datang di Stock Game."
print "Anda mau [M]ain atau Baca [A]turan?"
answer= raw_input(">")
answerRecognizerOne(answer)
#
def answerRecognizerOne(inbox):
inbox.lower()
if inbox=="a":
ruleExplainer()
elif inbox=="m":
gameStarter()
else:
loopingSpace()
print "Syntax tidak dimengerti. Mohon ulangi."
loopingSpace()
startingTheGame()
#
def answerRecognizerTwo(inbox):
inbox.lower()
if inbox=="y":
print "Kita akan mengambil kartu kesempatan lagi"
cekKartuKesempatan()
elif inbox=="n":
print "Game akan dilanjutkan"
#
def ruleExplainer():
loopingSpace()
print "Aturan:"
print "Dalam awal giliran kamu, kamu akan mengambil kartu kesempatan."
print "Kartu kesempatan kamu akan memberikan kamu hak untuk mengubah harga saham."
print "Lalu kamu bisa jual atau beli saham."
print "Kamu juga dapat bekerja pada Weekend, sehingga kamu dapat uang tambahan."
print "Setelah 33 hari. Peserta dengan uang tertinggi akan menang."
loopingSpace()
startingTheGame()
#
def gameSetUp():
playerOne=[250,0,0]
playerOne[2]=playerOne[0]+playerOne[1]
playerTwo=[250,0,0]
playerTwo[2]=playerTwo[0]+playerTwo[1]
playerThree=[250,0,0]
playerThree[2]=playerThree[0]+playerThree[1]
price=[30,30,30,30,30,30,30,30]
print playerOne
print playerTwo
print playerThree
print price
loopingSpace()
print "Saya akan memberi kamu semua $250 untuk berinvestasi."
print "Kamu juga akan memasuki dunia Wallsheet."
print "Sebuah bursa saham di dunia Kryxban."
print "Semoga beruntung."
loopingSpace()
answer= raw_input ("Tekan enter untuk melanjutkan")
clockTracker=[1,0]
print "Good Luck"
loopingSpace()
kartuKesempatan()
#
def refreshScore():
playerOne[1]=0
for i in range(8):
playerOne[1]+=(stockOne[i]*price[i])
playerTwo [1]=0
for i in range(8):
playerTwo[1]+=(stockTwo[i]*price[i])
playerThree [1]=0
for i in range(8):
playerThree[1]+=(stockThree[i]*price[i])
playerOne[2] = playerOne[0] + playerOne[1]
playerTwo[2] = playerTwo[0] + playerTwo[1]
playerThree[2] = playerThree[0] + playerThree[1]
# Fungsi printScore -> Mengprint skor
def printScore():
print playername[0]+": Uang: $"+str(playerOne[0])+" Saham: $"+str(playerOne[1])+" Total: $"+str(playerOne[2])
print playername[1]+": Uang: $"+str(playerTwo[0])+" Saham: $"+str(playerTwo[1])+" Total: $"+str(playerTwo[2])
print playername[2]+": Uang: $"+str(playerThree[0])+" Saham: $"+str(playerThree[1])+" Total: $"+str(playerThree[2])
# Fungsi kartuKesempatan -> Menjalankan fase Kartu Kesempatan
def kartuKesempatan ():
refreshScore()
print "Sekarang adalah giliran " + playername[clockTracker[1]]
print ""
printScore()
loopingSpace()
print "Kamu mengambil kartu kesempatan"
answer = raw_input ("Kamu siap? Tekan enter jika kamu siap?")
cekKartuKesempatan()
#
def gameStarter():
print loopingSpace()
for i in range(3):
answer= raw_input("Masukan nama pemain ke " + str(i+1)+ ">")
playername.append(answer)
gameSetUp()
#
def cekKartuKesempatan():
foo = randint(1,2)
if foo==1:
print "**KAMU MENDAPAT $25**"
print "Dompet kamu tiba-tiba memberat."
print "Kamu mengecek dompetmu."
print "Ada $25 muncul!"
(listing[clockTracker[1]][0])+=25
updateScore()
checkForToool()
elif foo==2:
print "**SAHAM NAIK 10%**"
woo=0
for i in range(8):
woo= floor.(price[i]/10)
if woo != 0:
price[i] += woo
print "Saham "+stockName[i]+" naik $"+woo
checkForTool()
def checkForTool()
if (toolListing[clockTracker[1]][0])!=0:
print "Anda mempunyai 'Kesempatan Extra'. Mau dipakai? ( Anda punya "+str.(toolListing[clockTracker[1]][0])+" ) [y]es /[n]o"
answer= raw_input(">")
answerRecognizerTwo(answer)
It threw this error.
File "main.py", line 31
def loopingSpace():
^
SyntaxError: invalid syntax
Note: I use online executor
Note: The online executor respectively use 2.7.4 and 2.7.5
Where do I do wrong?
NOTE: When I delete the loopingSpace(): function from the code completely, it will then complain about the next function in line which in this case startingTheGame(), and so on
PS: This pyt is formed as a game. I will call one function (startingTheGame()) and this function will call other function and so on. I pretty sure you get the point.
Sincerely,
DEO

The syntax error is actually on the line before it:
stockName=["Alama Inc.","Bwah! Bwah! Bwah! LCD","CUIT! CUIT CV",
"Dong Inc.","Eeeeeeeeeeeeah!","Foo il company.",
"Gogogogo Ind.","Halllo."
You have to add a closing bracket ]:
stockName=["Alama Inc.","Bwah! Bwah! Bwah! LCD","CUIT! CUIT CV",
"Dong Inc.","Eeeeeeeeeeeeah!","Foo il company.",
"Gogogogo Ind.","Halllo."]

Currently, your list is defined as:
stockName=["Alama Inc.","Bwah! Bwah! Bwah! LCD","CUIT! CUIT CV","Dong Inc.","Eeeeeeeeeeeeah!","Foo il company.","Gogogogo Ind.","Halllo."
Notice how there is no ] at the end of the list. Thus, you have technically not defined the list yet, and so python tries to continue making the list. It then reads the next line with text, which is def loopingSpace():. As the syntax [..., "Halllo." def loopingSpace() isn't proper syntax, a SyntaxError is raised at the line of definition.

Related

i am making a search but when printing why does the second input also come in

The code I am using is as follow:
elif (menu == 4):
cari = input("Masukan Data Mahasiswa Yang Akan Dicari : ")
for mhs in data_semua_mhs:
if (mhs["nim"]==cari):
print('Nim : ',mhs['nim'])
print('Nama : ',mhs['nama'])
print('Gender : ',mhs['gender'])
print('Ipk : ',mhs['ipk'])
elif (mhs["nim"]!=cari):
print("Data Tidak Tersedia")
enter image description here
So you want to print "Data Tidak Tersedia" (data not available) if no student record is found, but you current system is the following: go through every student in the list. If it matches the id, print the data. If it does not match, print that the data is not available. However, this will print this for every student that does not match.
The following will print it only if no students match:
elif (menu == 4):
cari = input("Masukan Data Mahasiswa Yang Akan Dicari : ")
ada = False
for mhs in data_semua_mhs:
if (mhs["nim"]==cari):
ada = True
print('Nim : ',mhs['nim'])
print('Nama : ',mhs['nama'])
print('Gender : ',mhs['gender'])
print('Ipk : ',mhs['ipk'])
if ada is False:
print("Data Tidak Tersedia")

How do I remove the last character of a variable until there is only one left in python

I am working on a program that prints every possible combination of a word. Everything works, but I wanted to take it a step further so it doesn't only print all combinations of a word. It should remove the last character of a word until there is only one letter left.
Here is what I have written:
# Enter Word
print("Enter your word:")
print()
s = input(colorGreen)
# If s is a string, print all combinations
if all(s.isalpha() or s.isspace() for s in s):
t=list(itertools.permutations(s,len(s)))
for i in range(0,len(t)):
print(colorGreen + "".join(t[i]))
while len(s) != 1:
t=list(itertools.permutations(s,len(s)))
for i in range(0,len(t)):
print(colorGreen + "".join(t[i]))
print()
print("Finished!")
print()
input("Press anything to quit...")
# If s is not a string, print error
if not all(s.isalpha() or s.isspace() for s in s):
print(colorRed + "You did not enter a correct word")
print("Only use a word for Word combinations")
print("Please restart the program.")
print()
input("Press anything to quit...")
Thanks in advance :D
You can do it this way:
from itertools import permutations
string = 'hello'
c = reversed([''.join(s) for i in range(1,len(string)+1) for s in permutations(string,i)])
print('\n'.join(c))
Output:
olleh
ollhe
olelh
olehl
olhle
olhel
olleh
ollhe
olelh
olehl
olhle
olhel
oellh
oelhl
oellh
oelhl
oehll
oehll
ohlle
ohlel
ohlle
ohlel
ohell
ohell
loleh
lolhe
loelh
loehl
lohle
lohel
lloeh
llohe
lleoh
lleho
llhoe
llheo
leolh
leohl
leloh
lelho
lehol
lehlo
lhole
lhoel
lhloe
lhleo
lheol
lhelo
loleh
lolhe
loelh
loehl
lohle
lohel
lloeh
llohe
lleoh
lleho
llhoe
llheo
leolh
leohl
leloh
lelho
lehol
lehlo
lhole
lhoel
lhloe
lhleo
lheol
lhelo
eollh
eolhl
eollh
eolhl
eohll
eohll
elolh
elohl
elloh
ellho
elhol
elhlo
elolh
elohl
elloh
ellho
elhol
elhlo
eholl
eholl
ehlol
ehllo
ehlol
ehllo
holle
holel
holle
holel
hoell
hoell
hlole
hloel
hlloe
hlleo
hleol
hlelo
hlole
hloel
hlloe
hlleo
hleol
hlelo
heoll
heoll
helol
hello
helol
hello
olle
ollh
olel
oleh
olhl
olhe
olle
ollh
olel
oleh
olhl
olhe
oell
oelh
oell
oelh
oehl
oehl
ohll
ohle
ohll
ohle
ohel
ohel
lole
lolh
loel
loeh
lohl
lohe
lloe
lloh
lleo
lleh
llho
llhe
leol
leoh
lelo
lelh
leho
lehl
lhol
lhoe
lhlo
lhle
lheo
lhel
lole
lolh
loel
loeh
lohl
lohe
lloe
lloh
lleo
lleh
llho
llhe
leol
leoh
lelo
lelh
leho
lehl
lhol
lhoe
lhlo
lhle
lheo
lhel
eoll
eolh
eoll
eolh
eohl
eohl
elol
eloh
ello
ellh
elho
elhl
elol
eloh
ello
ellh
elho
elhl
ehol
ehol
ehlo
ehll
ehlo
ehll
holl
hole
holl
hole
hoel
hoel
hlol
hloe
hllo
hlle
hleo
hlel
hlol
hloe
hllo
hlle
hleo
hlel
heol
heol
helo
hell
helo
hell
oll
ole
olh
oll
ole
olh
oel
oel
oeh
ohl
ohl
ohe
lol
loe
loh
llo
lle
llh
leo
lel
leh
lho
lhl
lhe
lol
loe
loh
llo
lle
llh
leo
lel
leh
lho
lhl
lhe
eol
eol
eoh
elo
ell
elh
elo
ell
elh
eho
ehl
ehl
hol
hol
hoe
hlo
hll
hle
hlo
hll
hle
heo
hel
hel
ol
ol
oe
oh
lo
ll
le
lh
lo
ll
le
lh
eo
el
el
eh
ho
hl
hl
he
o
l
l
e
h

Python - Append input to .txt but deletes prior data

I´m trying to append input to a .txt and succeed to do so, however the data previously present in my .txt file gets overwritten by the data inputted. I wish for the data to stay with the input added.
Heres my code so far:
def tilføjMedlem():
while True:
tilføjFornavn = input("Skriv fornavn på det medlem du ønsker at tilføje: (Tast q for at afslutte)")
if tilføjFornavn == 'q':
break
else:
tilføjEfternavn= input("Efternavn:")
tilføjJollypoints= input("Jollypoints:")
tilføjInstagram = input("Instagram:")
tilføjMedlemSiden = input('Medlem siden:')
with open('fans.txt', 'a') as text_file:
text_file.write(tilføjFornavn+" "+tilføjEfternavn+" "+tilføjJollypoints+" "+tilføjInstagram+" "+tilføjMedlemSiden)
tilføjMedlem()
You need to fix the indentation of the with open() function.
Your code is re-assigning the values to variables you have declared. It will call write to file function only once with the last values entered in the variables after user had entered q to quit.
def tilføjMedlem():
while True:
tilføjFornavn = input("Skriv fornavn på det medlem du ønsker at tilføje: (Tast q for at afslutte)")
if tilføjFornavn == 'q':
break
else:
tilføjEfternavn= input("Efternavn:")
tilføjJollypoints= input("Jollypoints:")
tilføjInstagram = input("Instagram:")
tilføjMedlemSiden = input('Medlem siden:')
with open('fans.txt', 'a') as text_file:
text_file.write(tilføjFornavn+" "+tilføjEfternavn+" "+tilføjJollypoints+" "+tilføjInstagram+" "+tilføjMedlemSiden)
tilføjMedlem()
The code work
Actually, the code append the text correctly to the .txt file. But it overwrite the previous input you may enter in the while loop.
If the input getter behave like intended, then there is no issues with your code. It get the 4 last inputs you enter, then append them in the file without overwriting it:
however the data previously present in my .txt file gets overwritten by the data inputted
This is false. Your code works.
Here is what I executed:
def tilføjMedlem():
while True:
tilføjFornavn = input("Skriv fornavn på det medlem du ønsker at tilføje: (Tast q for at afslutte)")
if tilføjFornavn == 'q':
break
else:
tilføjEfternavn= input("Efternavn:")
tilføjJollypoints= input("Jollypoints:")
tilføjInstagram = input("Instagram:")
tilføjMedlemSiden = input('Medlem siden:')
with open('fans.txt', 'a') as text_file:
text_file.write(tilføjFornavn+" "+tilføjEfternavn+" "+tilføjJollypoints+" "+tilføjInstagram+" "+tilføjMedlemSiden)
tilføjMedlem()
Original file:
This is the original data
Script execution:
Skriv fornavn på det medlem du ønsker at tilføje: (Tast q for at afslutte)
>>>? n
Efternavn:
>>>? First input
Jollypoints:
>>>? second input
Instagram:
>>>? third input
Medlem siden:
>>>? and this is the last one.
Skriv fornavn på det medlem du ønsker at tilføje: (Tast q for at afslutte)
>>>? q
Final file:
This is the original data
q First input second input third input and
this is the last one.
If the intended behavior is that EVERY inputs append to the file, you have to change the indent of the with block:
def tilføjMedlem():
while True:
tilføjFornavn = input("Skriv fornavn på det medlem du ønsker at tilføje: (Tast q for at afslutte)")
if tilføjFornavn == 'q':
break
else:
tilføjEfternavn= input("Efternavn:")
tilføjJollypoints= input("Jollypoints:")
tilføjInstagram = input("Instagram:")
tilføjMedlemSiden = input('Medlem siden:')
with open('fans.txt', 'a') as text_file:
text_file.write(tilføjFornavn+" "+tilføjEfternavn+" "+tilføjJollypoints+" "+tilføjInstagram+" "+tilføjMedlemSiden)
tilføjMedlem()

ValueError trying to split the lines of a text file

This is my code:
def MusicGame():
score=0
tries = 0
with open("songs.txt") as file:
for line in file.readlines():
artist,name=line.split(" - ", 1)
question=(artist + "- " + " ".join([x[0].upper() for x in name.split()])+": ")
answer=input(question)
if tries != 2:
if answer in ["STOOPID","Funky Friday","dark knight dummo","natural disaster","gucci gang"]:
print("well done")
tries=0
score=score+3
elif answer not in ["STOOPID","Funky Friday","dark knight dummo","natural disaster","gucci gang"]:
answer2=input("it was wrong try again")
if answer in ["STOOPID","Funky Friday","dark knight dummo","natural disaster","gucci gang"]:
print("well done+1")
tries=tries+1
score=score+1
elif answer2 not in ["STOOPID","Funky Friday","dark knight dummo","natural disaster","gucci gang"]:
print("you suck you lost")
break
I keep getting this error
artist,name=line.split(" - ", 1)
ValueError: need more than 1 value to unpack
My text file looks like this:
6ix9ine,Bobby Shmurda - STOOPID
Dave,Fredo - Funky Friday
Trippie Redd,Travis Scott - Dark Knight Dummo
NSG - Natural Disaster
Lil pump - Gucci Gang
It looks like your file has empty lines. You can't split those on '-' and unpack the result into two variables because these lines don't contain that character. Filter out the empty lines first.
Demo:
>>> def non_blank(file):
... return (line for line in file if line.strip())
...
>>> with open('songs.txt') as songs:
... for line in non_blank(songs):
... print(line.split(' - '))
...
['6ix9ine,Bobby Shmurda', 'STOOPID\n']
['Dave,Fredo', 'Funky Friday\n']
['Trippie Redd,Travis Scott', 'Dark Knight Dummo\n']
['NSG', 'Natural Disaster\n']
['Lil pump', 'Gucci Gang\n']

Problem with writing to file second time, Python3

I have created a phonebook with tkinker using Python 3.6
When I add persons to phonebook it save it to a file.
When I load the program again it loads the file as it should.
If I add 2 person at first run, all works fine.
Second run, I add one person and it adds an empty line at index 1 and adds the person below as it should.
Third run, I add one person, it adds a new line at index 1 and a person last in the list.
Now I get 2 empty lines.
I can't figure out why it creates an empty space at index 1 . It should not do it.
Here is the code, comments are in Swedish so sorry about it.
How I write to the file is in function lägg_till()
It will auto create kontakter.txt when you run it first time.
"Lägg till" means add in Sweden and "Avsluta" is quit the program.
from tkinter import *
import os.path
root = Tk()
root.geometry("640x640+200+100")
root.title("Telefon listan")
def avsluta():
quit()
def spara():
#Spara kontakter till fil.
name = entry_1.get()
mobil = entry_2.get()
if name == "" or mobil == "" :
pass
else:
with open("kontakter.txt","w") as file:
file.write("\n".join(kontakter.get(0,END)))
def ta_bort():
# Ta bort kontakter,genom att välja index av element och sparar värdet i variabel index.
index = kontakter.curselection()
print(index)
kontakter.delete(index)
def lägg_till():
# Ta inmatade värden från name,mobil och spara i kontakter.
# Använder .get() för att hämta
name = entry_1.get()
mobil = entry_2.get().replace(" ", "") # Använder replace för att rensa whitespace
# Varning när alla värden inte är ifyllda
if name == "" or mobil == "" :
label_error.config(text="Alla fälten är inte ifyllda")
else:
# trycka in dessa i kontakter med .insert() END för slutet av listan, dvs index "kan vara 0,1,2,3"
#Rensar error fältet innan man lägger till kontakten
label_error.config(text="")
kontakter.insert(END,name + " - " + mobil)
# Rensa fältet efter lägg till
entry_1.delete(0,END)
entry_2.delete(0,END)
kontakt = kontakter.get(0,END)
with open("kontakter.txt","w") as file:
file.write("\n".join(kontakt))
def uppdatera():
# Hämta det markerade data
index = kontakter.curselection()
name = entry_1.get()
mobil = entry_2.get()
# Varning när alla värden inte är ifyllda
if name == "" or mobil == "" :
label_error.config(text="Alla fälten är inte ifyllda")
else:
# trycka in dessa i kontakter med .insert() END för slutet av listan, dvs index "kan vara 0,1,2,3"
#Rensar error fältet innan man lägger till kontakten
label_error.config(text="")
# Raderar det ifyllda data
kontakter.delete(index)
#Skriver nytt
kontakter.insert(index,name + "-" + mobil)
entry_1.delete(0,END)
entry_2.delete(0,END)
# Skapar frame
#Namn
fram_1 = Frame(root)
fram_1.pack()
#Mobil
fram_2 = Frame(root)
fram_2.pack()
#Knappar
fram_3 = Frame(root)
fram_3.pack()
# Listbox
fram_4 = Frame(root)
fram_4.pack()
#Skapar label
#Namn
label_1 = Label(fram_1,text="Name:")
label_1.grid(row=0, column=0)
#Mobil
label_2 = Label(fram_2,text="Mobil:")
label_2.grid(row=1,column=0)
# Skapar entry
#namn
entry_1 = Entry(fram_1)
entry_1.grid(row=0,column=1)
#Mobil
entry_2 = Entry(fram_2)
entry_2.grid(row=1,column=2,)
# Kolla om filen finns, annars skapa den, behöver importera os.path
if not os.path.exists("kontakter.txt"):
open('kontakter.txt', 'w').close()
else:
pass
# Läsa från fil
data = []
with open("kontakter.txt" ,"r") as fil:
for line in fil:
data += [line]
# Listbox
kontakter = Listbox(fram_4,height=8,width=40,bg="pink")
kontakter.grid(row=0,column=0)
# Lägger till kontakter , första värdet är index följt av värde,
kontakter.insert(END,)
#Läsa in från fil
for i in range(len(data)):
kontakter.insert(i+0 , data[i])
# Error
label_error = Label(root,text="",fg="red")
label_error.pack()
# Knappar
# knapp Lägg till
button_1 = Button(fram_3,text="Lägg till",command=lägg_till)
button_1.grid(row=0,column=0)
# knapp edit
button_2 = Button(fram_3,text="Uppdatera",command=uppdatera)
button_2.grid(row=0,column=1)
# Knapp delete
button_3 = Button(fram_3,text="Radera",command=ta_bort)
button_3.grid(row=0,column=2)
# Knapp avsluta
button_4 = Button(fram_3,text="Avsluta",command=avsluta)
button_4.grid(row=0,column=3)
button_5 = Button(fram_3,text="Spara",command=spara)
button_5.grid(row=0,column=4)
root.attributes("-topmost", True)
root.mainloop()
Inside lägg_till() when you open the file use ab instead of w:
with open("kontakter.txt","ab") as file:
file.write("\n".join(kontakt))
By adding .strip() , I made workaround, but I think problem is still there.
# Läsa från fil
data = []
with open("kontakter.txt" ,"r") as fil:
for line in fil.readlines():
data += [line.strip()] #.strip() fix the problem
fil.close()
The problem in your program is kontakt = kontakter.get(0,END), which returns your data as follows :
('1 - 1\n', '2 - 2', '3 - 3')
Note that the third entry (3 - 3) is made after the GUI was closed once. By joining together with '\n'.join(), you get an additional space character:
'1 - 1\n\n2 - 2\n3 - 3\n'
I don't know the exact reason why this only happens if you close the program once.
You can avoid this conflict by using 'a' instead of 'w', which simply appends the string in the text file.
with open("kontakter.txt","a") as file:
file.write(name + " - " + mobil + '\n')

Categories