Error writing text into a .txt file in python - python-3.x

I am making a program that will
1. Create a text file
2. Allow a password to be stored
3. Allow a password to be changed
4. Add an additional password
5. Delete a specific password
The problem is in def delete():. I put in three passwords on three seperate lines: first, second, third. When I choose to delete password "second", it reprints the list from before, and then prints the new list at the end of the last password.
Here is my code:
import time
def create():
file = open("password.txt", "w")
passwordOfChoice = input("The password you want to store is: ")
file.write(passwordOfChoice)
print ("Your password is: ", passwordOfChoice)
file.close()
time.sleep(2)
def view():
file = open("password.txt","r")
print ("Your password is: ",
"\n", file.read())
file.close()
time.sleep(2)
def change():
file = open("password.txt", "w")
newPassword = input("Please enter the updated password: ")
file.write(newPassword)
print ("Your new password is: ", newPassword)
file.close()
time.sleep(2)
def add():
file = open("password.txt", "a")
extraPassword = input("The password you want to add to storage is: ")
file.write("\n")
file.write(extraPassword)
print ("The password you just stored is: ", extraPassword)
file.close()
time.sleep(2)
def delete():
phrase = input("Enter a password you wish to remove: ")
f = open("password.txt", "r+")
lines = f.readlines()
for line in lines:
if line != phrase+"\n":
f.write(line)
f.close()
print("Are you trying to: ",
"\n1. Create a password?",
"\n2. View a password?",
"\n3. Change a previous password?",
"\n4. Add a password?",
"\n5. Delete a password?",
"\n6. Exit?\n")
function = input()
print("")
if (function == '1'):
create()
elif (function == '2'):
view()
elif (function == '3'):
change()
elif (function == '4'):
add()
elif (function == '5'):
delete()
elif (function == '6'):
print("Understood.", "\nProgram shutting down.")
time.sleep(1)
else:
print("Your answer was not valid.")
print("Program shutting down...")
time.sleep(1)
To show what I meant above, here is my output:
Your password is:
first
second
thirdfirst
third
Can someone please tell me how to fix my def delete(): function so that it will not rewrite the original data? Thanks a ton!

The problem lies with the 'r+' mode. When you use 'r+' you can read and write, sure, but it's up to you to control where in the file you write.
What's happening is you read the file, and the cursor is stuck at the end, so when you write it back, Python dutifully puts your new lines on the end of the file.
See the docs about file methods; you're looking for something like seek.

Related

Python3 with Loop function / password exit?

I'm new to Python and need a little help. I came across this code on here which I kind of understand and want to expand on it... but I don't know how to get out of the loop!
When you run the code and enter the specified username and password, it runs the defined function logged()... but then loops back to asking for the username again because it run the main() function again!... how can I get past this. When the correct username & password is entered, I would like to be at a point where I can add new code! Does this make sense?
import os
import time
#Must Access this to continue.
def main():
while True:
UserName = input ("Enter Username: ")
PassWord = input ("Enter Password: ")
if UserName == 'Bob' and PassWord == 'rainbow123':
time.sleep(1)
print ("Login successful!")
logged()
else:
print ("Password did not match!")
def logged():
time.sleep(1)
print ("Welcome to ----")
main()
When all matches, break out of loop and call logged outside the loop. Or else once the logged is over, you return back to the infinite loop again.
def main():
while True:
UserName = input ("Enter Username: ")
PassWord = input ("Enter Password: ")
if UserName == 'Bob' and PassWord == 'rainbow123':
time.sleep(1)
print ("Login successful!")
break
else:
print ("Password did not match!")
logged()

CRUD program to read,write and append the details in txt file

It's a school assignment, an event management system. It will write the data to a txt file and retrieve it. Its mostly a CRUD program but not sure why it is not running. It shows space as an error on VS CODE IDE.
It will Create a customer, ask for the seats that he want to book. He can also delete the seats as per ref number before 24 hours.
import random
print("Welcome to the Event System")
def menu():
print("Choose the number from menu")
print("1:Create Customer")
print("2:Reserve a seat")
print("3.Cancel the seat")
print("4.Exit the Event System")
option = input("put down the number")
return option
def executingmenuinputchoice(option):
if(option == 1):
createcust()
elif(option == 2):
reserveseat()
elif(option == 3):
cancelseat()
elif(option == 4):
exit()
else:
print('you have chose a wrong option')
menu()
def createcust():
print('Provide Customer details')
name = input('Full name? --> ')
pno = input('phone number? -> ')
email = input('Email Id? --> ')
try:
file = open("cust.txt", "r")
lines = file.read().splitlines()
last_lines = lines[-1]
content = last_lines.split()
refno = random.randint(10001, 99999)
file.close()
file = open("cust.txt", "a")
file.write("\n"+" "+name+" "+pno+" "+email+" "+refno)
file.close()
print(refno + 'is your reference number')
print('Added Customer to file')
except IOError:
print("File doesn't exist at location")
except TypeError:
print('input proper data')
return createcust()
def customerexist(refno):
try:
file = open("cust.txt", "r")
for line in file:
content = line.split()
if (refno == int(content[4])):
file.close()
return True,int(content[5])
except IOError:
print("File doesn't exist")
file.close()
return False,0
def reserveseat():
referencenumber=input("Enter the Reference Number-->")
refexist =referenceexist(referencenumber)
if(refexist==True):
seatsyouwantbook=input("Number of seats you want to book? ->")
date=datetime.datetime.now()
seats=seats+seatsyouwantbook
newline=""
try:
file=open("cust.txt","r")
lines=file.read().splitlines()
last_linesno=len(lines)
currentLine=1
for line in lines:
content=line.split
if(currentline!=last_linesno):
if(refno==int(content[4])):
file.close()
return True,int(content[5])
except IOError:
print("FIle never existed")
file.close()
return False,0
def cancelseat():
try:
file=open("cust.txt","r")
for line in file:
content=line.split()
if (refno==int(content[4])):
file.close()
return True,int(content[5])
except IOError:
print("File doesn't exist")
file.close()
return False,0
invalid syntax (<unknown>, line 41)
I want it to run properly so, I can submit it again.
I haven't checked your whole code, but at least got it running to the point that you could further rectify it:-
import random
print("Welcome to the Event System")
def customerexist(refno):
try:
file = open("cust.txt", "r")
for line in file:
content = line.split()
if (refno == int(content[4])):
file.close()
return True,int(content[5])
except IOError:
print("File doesn't exist")
file.close()
return False,0
def reserveseat():
referencenumber=input("Enter the Reference Number-->")
refexist =referenceexist(referencenumber)
if(refexist==True):
seatsyouwantbook=input("Number of seats you want to book? ->")
date=datetime.datetime.now()
seats=seats+seatsyouwantbook
newline=""
try:
file=open("cust.txt","r")
lines=file.read().splitlines()
last_linesno=len(lines)
currentLine=1
for line in lines:
content=line.split
if(currentline!=last_linesno):
if(refno==int(content[4])):
file.close()
return True,int(content[5])
except IOError:
print("FIle never existed")
file.close()
return False,0
def cancelseat():
try:
file = open("cust.txt","r")
for line in file:
content=line.split()
if (refno==int(content[4])):
file.close()
return True,int(content[5])
except IOError:
print("File doesn't exist")
file.close()
return False,0
def createcust():
print('Provide Customer details')
name = input('Full name? --> ')
pno = input('phone number? -> ')
email = input('Email Id? --> ')
try:
file = open("cust.txt", "r")
lines = file.read().splitlines()
last_lines = lines[-1]
content = last_lines.split()
refno = random.randint(10001, 99999)
file.close()
file = open("cust.txt", "a")
file.write("\n"+" "+name+" "+pno+" "+email+" "+refno)
file.close()
print(refno + 'is your reference number')
print('Added Customer to file')
except IOError:
print("File doesn't exist at location")
except TypeError:
print('input proper data')
return createcust()
def menu():
print("Choose the number from menu")
print("1:Create Customer")
print("2:Reserve a seat")
print("3.Cancel the seat")
print("4.Exit the Event System")
option = input("put down the number")
return option
def executingmenuinputchoice(option):
option = int(option)
if(option == 1):
createcust()
elif(option == 2):
reserveseat()
elif(option == 3):
cancelseat()
elif(option == 4):
exit()
else:
print('you have chose a wrong option')
menu()
executingmenuinputchoice(menu())
REASON FOR ERRORS:-
Your indentation was all over the place, python language
prioritizes indentation as it uses it to figure out a block span, so you should
keep a consistent indentation scheme throughout your code.
Python uses top down approach for ~interpreting the
program, i.e. It only keeps track of the stuff that it had already
encountered. In your code, the function executingmeninputchoice()
and menu() (the two primary functions used for UI) were stacked
above all other function, therefore when you tried to call other
function from these two function, they aren't called. As the program
doesn't know whether these functions exists or not (as it hasn't
encountered them yet)
A logical error existed in function
executingmenuinputchoice(option) as you were trying to take in
input a string and were comparing it with integer values, and
therefore every time the operation failed and the control got shifted
to the else block, therefore every time you got the same output
'you have chose a wrong option' regardless of whether the input was
legal or not
P.S.:- I haven't tested your full code, as this isn't a code for me service, other logical errors may also exist, so I would recommend you to find and fix those too.

How do I make my python program to write a new file

I am writing a program by which I can extract data from a file, and then based on some condition, I have to write that data to other files. These files do not exist and only the code will create these new files. I have tried every possible combination of print parameters but nothing is helping. The program seems to run fine with no error in IDLE but no new files are created. Can somebody give me a solution?
Here is my code:
try:
data= open('sketch.txt')
for x in data:
try:
(person, sentence)= x.split(':',1)"""data is in form of sentences with: symbol present"""
man=[] # list to store person
other=[] #list to store sentence
if person=="Man":
man.append(sentence)
elif person=="Other Man":
other.append(sentence)
except ValueError:
pass
data.close()
except IOError:
print("file not found")
try:
man_file=open("man_file.txt","w")""" otherman_file and man_file are for storing data"""
otherman_file=open("otherman_file.txt", "w")
print(man,file= man_file.txt)
print(other, file=otherman_file.txt)
man_file.close()
otherman_file.close()
except IOError:
print ("file error")
2 problems
you should use
man_file = open("man_file.txt", "w+")
otherman_file = open("otherman_file.txt", "w+")
w+ - create file if it doesn't exist and open it in write mode
Modes 'r+', 'w+' and 'a+' open the file for updating (reading and writing); note that 'w+' truncates the file..
https://docs.python.org/2/library/functions.html
2.
print(man,file= man_file.txt)
print(other, file=otherman_file.txt)
if sketch.txt file do not exist then "man" and "other" will not initialized
and in the print method will throw another exception
try to run this script
def func():
man = [] # list to store person
other = [] # list to store sentence
try:
data = open('sketch.txt', 'r')
for x in data:
try:
(person, sentence) = x.split(':', 1)
if person == "Man":
man.append(sentence)
elif person == "Other Man":
other.append(sentence)
except ValueError:
pass
data.close()
except IOError:
print("file not found")
try:
man_file = open("man_file.txt", "w+")
otherman_file = open("otherman_file.txt", "w+")
# print(man, man_file.txt)
# print(other, otherman_file.txt)
man_file.close()
otherman_file.close()
except IOError:
print ("file error")
func()

How to recieve files from a server in python?

I Have made a python script, where you can send files to a remote server and receive them. I can send them to the server but can not seem to retrieve them back I've attached both server and client.py
Server.py
import socket # Import socket module
import os
s = socket.socket()
s.bind(('139.59.173.187', 8010)) # Binds port and IP address
s.listen(3) #wait for client to join
c, addr = s.accept()
def RecvFile():
print ("File is comming ....")
file = c.recv(1024) #recieves file name from client
print(file)
f = open(file,'wb') #open that file or create one
l = c.recv(4096) #now recieves the contents of the file
while (l):
print ("Receiving...File Data")
f.write(l) #save input to file
l = c.recv(4096) #get again until done
print("The file",file,"has been succesfully saved to the server\nConnection from:",addr)
f.close()
def SendFile():
file = c.recv(1024)
print(file)
with open(file,'rb') as f:
c.sendall(f.read())
print("File has been sent to the client:", addr)
main()
def main():
option = str(c.recv(1024), 'utf-8')
print(option)
if option[:1] == "R":
SendFile()
elif option[:2] == "S":
RecvFile()
main()
s.close()
Client.py
import time
import socket
import sys
import urllib.request
#import paramiko
def login():
a = 1
while a == 1:
global user
user = input("Username:")
passw = input("Password:")
with open('User.txt') as f:
for line in f.readlines():
us, pw = line.strip().split("|", 1)
if (user == us) and (passw == pw):
print("login Successful!")
a = a+1
main()
return
print("Incorrect details, Try again!")
def register():
print("You will recieve a generated Username from your Name and age")
regName = input("First Name: ")
regAge = input("Age: ")
regPass = input("Password: ")
regUser = (regName[0:3]+regAge)
with open('User.txt', 'a') as file:
file.writelines(regUser+"|"+regPass+"\n")
print("You have Succesfully registered")
print("Your Username is:"+regUser)
print("Your Password is:"+regPass)
print("!Please keep these credentials secure!")
def main():
print("=========================Welcome to Bluetooth Projector=========================")
option = input("Here are your options:\n--> Press C to connect to the projector\n--> Press F for File System")
x = 1
while x == 1:
if option == "C" or option == "c":
optionc(x)
elif option == "F" or "f":
File_System()
def optionc():
print("Loading.....")
time.sleep(2)
print("Obtaining IP addres.....")
time.sleep(2)
print("Connecting.....")
time.sleep(3)
print("Connected")
x = x+1
def File_System():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('139.59.173.187',8010))
print("=========================Welcome to the File System =========================")
option = input("Here are your options:\n--> Press S to upload files\n--> Press R to retrieve files")
if option == "S" or option == "s":
s.send("S".encode('utf-8'))
file_name = input("Please input the file name\n>>>")
name = input("What would you like it to be saved as?\n>>>")
s.send(name.encode('utf-8'))
with open(file_name,'rb') as f:
s.sendall(f.read())
print("File has been sent to the server")
main()
elif option == "R" or option == "r":
s.send("R".encode('utf-8'))
filename = input("What is the filename you wish to recieve\n>>>")
s.send(filename.encode('utf-8'))
print ("File is comming ....")
f = open(filename,'wb') #open that file or create one
l = s.recv(1024) #now recieves the contents of the file
while (l):
print ("Receiving...File Data")
f.write(l) #save input to file
l = s.recv(1024)
print("The file",filename,"has been succesfully saved to your computer")
f.close()
while True:
check = input("Do you already have an account? Y/N \n ")
if check == "Y" or check == "y":
login()
break
elif check == "N" or check == "n":
register()
break
else:
print("pleae enter either Y or N")
Please look at the Filesystem() in the client file. I think it is receiving the second wave of bytes when getting files that is the problem
an was error is either broken pipe which I fixed.
But now the actually receiving file loop doesn't go through and stops getting the file bytes. I believe this is my error. I am confused however since my code is pretty much identical to sending the file to the server which has no complications.
But now the actually receiving file loop doesn't go through and stops getting the file bytes. I believe this is my error.
You are right. The client gets no indication that there aren't more file contents to come, and thus keeps on waiting in recv forever. To rectify this, you can let the server shut down the connection when the file has been sent, or, if you want the connection to be kept, inform the client about when it has to stop receiving, e. g. by sending it the file length beforehand.

Issue With Function Continuation in Python

I know this is probably a very simple fix, but I cannot seem to make the code work. Here is the problematic excerpt:
def main_menu():
print("Welcome! Please Choose An Option to Proceed")
print("1. New: Input Letters Into A New Excel Document")
print("2. Add: Add New Letters To An Existing Excel Document")
while True:
choice = input("Enter Option Number: ")
if choice.lower() in ['1','2']:
return choice.lower()
else:
print("Invalid Number Choice")
continue
def menu_choice(main_menu):
while True:
choice = main_menu()
if choice == "1":
newsession()
elif choice == "2":
addsession()
else:
break
def newsession():
while True:
try:
txtfilenameinput = input("1. Enter 'Txt' Input File Name: ")
inputfilename = txtfilenameinput.replace(".txt" , "")
inputfile = codecs.open(inputfilename + ".txt" , "r" , encoding = "utf-8" , errors = "ignore")
print("File Found" + "\n")
break
except FileNotFoundError:
print("File Not Found: Make Sure The File Is Spelled Correctly And That Both The Program and File Is On The Desktop Screen" + "\n")
if __name__ == '__main__':
main_menu()
closeprogram = input("Press Enter Key To Close Program")
My objective is, for example, when an input of "1" is inserted in main_menu(), the script would then start to run the newsession() function. Yet for some reason, the program does nothing but jumps to the end of the script (a "press key to close program" command) without engaging the newsession() function. This holds true for an input of "2" for the addsession() function as well. What am I doing wrong? I have tried everything but nothing allows my input choice of 1 or 2 to continue the progress in my script. Thank you for your help!
Try the code below. It allows to exit from the program and it returns again and again for more user input:
def main_menu():
print("Welcome! Please Choose An Option to Proceed")
print("1. New: Input Letters Into A New Excel Document")
print("2. Add: Add New Letters To An Existing Excel Document")
print(" QUIT with 'q'")
while True:
choice = input("Enter Option Number: ")
if choice.lower() in ['1','2','q']:
return choice.lower()
else:
print("Invalid Number Choice")
continue
def menu_choice(main_menu):
while True:
choice = main_menu()
if choice == "1":
newsession()
elif choice == "2":
addsession()
else:
break
The problem with your code was that you were "trapped" in a while True: loop with no escape. So after ONE single user choice newsession() or addsession() were started again and again with no further progress in the script and no way to change anything about it except to kill the program. Remember: each while True loop should have at least one line containing brake or return, else it is a never ending story ...
The problem with not reaching the newsession() is HERE:
if __name__ == '__main__':
main_menu()
where it should be:
if __name__ == '__main__':
menu_choice()

Resources