Xor Memory Error - python-3.x

This is my simple python xor encryption program, it works on every file i tried except when i used on an audio file which gave me a memory error, how do i fix it so it works on bigger files? The audio file i used it on was a wav audio file.
def encrypt(file,key):
count=0
encrypt=[]
openfile=open(file,"rb")
msg=openfile.read()
openfile.close()
for i in msg:
if count>=len(key):
count=0
encrypt.append(i^ord(key[count]))
count+=1
encryptmsg=''.join(chr(e) for e in encrypt)
ext=input('Saving...File Name (with extension)? ')
file= open(ext, "wb")
file.write(str.encode(encryptmsg))
file.close()
print(encryptmsg)
input("Press Enter to Continue...")
def decrypt(file,key):
count=0
decrypt=[]
openfile=open(file,"rb")
msg=openfile.read()
openfile.close()
for i in msg:
if count>=len(key):
count=0
decrypt.append(i^ord(key[count]))
count+=1
decryptmsg=''.join(chr(e) for e in decrypt)
ext=input('Saving...File Name (with extension)? ')
file= open(ext, "wb")
file.write(str.encode(decryptmsg))
file.close()
print(decryptmsg)
input("Press Enter to Continue...")
ans = input("0.Encrypt 1.Decrypt?")
file = input("File? ")
key = input("Key? ")
if ans=='0':
encrypt(file,key)
elif ans=='1':
decrypt(file,key)
else:
quit()

Related

Editing text files in python

I'm trying to edit text files in real time, like this text box here, you can write and edit any word you want and then save it to the file, think nano for linux. Anyone know a way of doing this?
I have no idea how to start so I haven't tried anything.
Also something simple please doesn't need to be crazy efficient.
The reading and current writing part of the script look like this:
f = open('./PYOS/startMessage.txt', 'r')
start_message = f.read()
print(start_message)
f.close()
while True:
user_input = str(input('P:\> '))
command = user_input.lower()
if command == 'read':
filename = input('Filename: ')
try:
file = open(filename, 'r')
cont = file.read(filename)
print('File contents: ', cont)
except FileNotFoundError:
print('File not found please try again')
elif command == 'write':
filename = input('Filename: ')
try:
file = open(filename, 'w')
write = input('Write in file: ')
cont = file.read(filename)
print('You wrote: ', cont)
except FileNotFoundError:
print('File not found please try again')

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 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.

Compressing a sentence into ascii and then decompressing it back

When I'm trying to compress this sentence into the ASCII equivalent, I keep getting this error code TypeError: ord() expected a character, but string of length 5 found
How can I fix the following code
def menu():
print("Compress a file Press 1")
print("Decompress a file Press 2")
print("Quit Press 3")
user_choice = input("")
if user_choice=="1":
compressing()
elif user_choice=="2":
decompressing()
elif user_choice=="3":
import sys
sys.exit()
else:
print("Input invalid.Please enter a number for path selection") , "\n" , menu()
def compressing():
compressed_sentence=[]
sentence=input("Enter a sentence: ")
sentence=sentence.split()
for i in range(len(sentence)):
character=(sentence[i])
ascii_character=ord(character)
compressed_sentence.append(ascii_character)
with open('compressed_file.txt','w') as myFile:
myFile.write(str(compressed_sentence))
menu()
def decompressing():
with open('compressed_file.txt','r') as myFile:
sentence=myFile.read()
for i in sentence:
if i in "[],'":
sentence=sentence.replace(i," ")
new_sentence=sentence.split()
decompressed_sentence=str("")
for i in range(len(new_sentence)):
character=int(new_sentence[i])
decompressed_sentence=(decompressed_sentence+(chr(character)))
final_decompressed_sentence=decompressed_sentence.split()
print(final_decompressed_sentence)
with open('decompressed_file.txt','w') as myFile:
myFile.write(final_decompressed_sentence)
menu()
menu()
in order for it to be able to compress and decompress it properly.
Its okay i got it working:
def menu():
print("Create a file Press 1")
print("Compress a file Press 2")
print("Decompress a file Press 3")
print("Quit Press 4")
user_choice = input("")
if user_choice=="1":
create_a_file()
elif user_choice=="2":
compressing()
elif user_choice=="3":
decompressing()
elif user_choice=="4":
import sys
sys.exit()
else:
print("Input invalid.Please enter a number for path selection") , "\n" , menu()
def create_a_file():
sentence=input("Enter a sentence: ")
sentence=sentence.split()
with open('file.txt','w') as myFile:
myFile.write(str(sentence))
menu()
def compressing():
compressed_sentence=[]
with open('file.txt','r') as myFile:
sentence=myFile.read()
for i in sentence:
if i in "[],'":
sentence=sentence.replace(i," ")
for i in range(len(sentence)):
character=(sentence[i])
ascii_character=ord(character)
compressed_sentence.append(ascii_character)
with open('compressed_file.txt','w') as myFile:
myFile.write(str(compressed_sentence))
menu()
def decompressing():
with open('compressed_file.txt','r') as myFile:
sentence=myFile.read()
for i in sentence:
if i in "[],'":
sentence=sentence.replace(i," ")
new_sentence=sentence.split()
decompressed_sentence=str("")
for i in range(len(new_sentence)):
character=int(new_sentence[i])
decompressed_sentence=(decompressed_sentence+(chr(character)))
final_decompressed_sentence=decompressed_sentence.split()
print(final_decompressed_sentence)
menu()
menu()

Error writing text into a .txt file in python

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.

Resources