Python file handling: output is not as expected. - python

I tried the following program on a file but didn't get the accurate result.
The decoded file is not the exact copy of the original message.
Some letters are eaten up somewhere.
"""
This file of python script works by encrypting the message in a below fashion:
Don't replace the characters in the even places.
Replace the characters in the odd places by their place numbers
. and if they exceed 'z', then again they will start from 'a'.
example: for a message "hello" would be "ieolt" and for message "maya" would be "naba"
import os
import time
import sys
def openfile(filename): # opens file with name 'filename'
file_to_open = open(filename,'a+')
return file_to_open
def readfile(filename): # returns a long string with the info of the message in 'filename' file.
time.sleep(0.3)
print "Reading from the file "+filename
reading_file = openfile(filename)
read_msg = reading_file.read()
return read_msg
def decode(msg): # returns decoded message of input message 'msg'.
""" reverse function of encode(msg) """
decoded_message = ""
letters = " abcdefghijklmnopqrstuvwxyz"
time.sleep(0.5)
print " Encoding ...."
print "encoding the message...."
index_of_msg = 0
for char in msg.lower():
if char.isalpha():
if index_of_msg%2 == 0 :
decoded_message += letters[(letters.rfind (char)- (index_of_msg+1))%26] # changed msg.rfind(char) to index_of_msg
else:
decoded_message += char
else:
decoded_message += char
index_of_msg +=1
time.sleep(0.5)
print "decoding completed"
return decoded_message
def encode(msg): # returns encoded message of input message 'msg'.
"""Clean up work must be done here.."""
encoded_message = ""
letters = " abcdefghijklmnopqrstuvwxyz"
time.sleep(0.5)
print " Encoding ...."
print "encoding the message...."
index_of_msg = 0
for char in msg.lower():
if char.isalpha():
if index_of_msg%2 == 0 :
encoded_message += letters[(letters.rfind(char)+ (index_of_msg+1))%26] # changed msg.rfind(char) to index_of_msg
else:
encoded_message += char
else:
encoded_message += char
index_of_msg +=1
time.sleep(0.5)
print "encoding completed"
return encoded_message
def write(msg,filename): # writes the message 'msg' given to it, to the file named 'filename'.
print "Opening the file "+filename
time.sleep(0.4)
file_output = openfile(filename)
print filename + " opened and ready to be written"
time.sleep(0.3)
print "Writing the encoded message to the file "+filename
file_output.write(msg)
file_output.close()
time.sleep(0.4)
print "Writing to the file has completed."
def start(): # Starter main function that incorporates all other functions :)
os.chdir('aaest/')
clear = lambda: os.system('clear')
clear()
print "Hi, Welcome to this Encryption Program. \n"
filename = raw_input("Enter the file name in which you stored the message: ")
print "Opening the file " + filename
time.sleep(0.5)
openfile(filename)
print filename +" opened up and ready, retrieving the message from it."
time.sleep(0.5)
message = readfile(filename)
print "The message of the "+filename+" is retrieved."
time.sleep(0.5)
encoded_msg = encode(message)
time.sleep(0.3)
decoded_msg = decode(encoded_msg)
encoded_file = raw_input("Enter the name of the output file in which encoded message will be saved :")
write(encoded_msg,encoded_file)
decoded_file = raw_input("Enter the name of the output file in which decoded message will be saved :")
write(decoded_msg,decoded_file)
start()
Can anyone please help me with this.

Part of your problem is that your letters strings begin with space rather than 'a'. So if you have a 'y' as the first character of the string, it gets replaced with a space. Then when you try to decode, the space fails your isalpha check and is not replaced.
There are a number of ways this code could be cleaner, but that's the first logical error I see. Unless I'm missing something, letters = "abcdefghijklmnopqrstuvwxyz" should fix that particular error. Or better yet, use string.ascii_lowercase.

Related

So i wrote a script and i need to fix it so it doesnt write in the script in string form, see the problem in its body

PyPython.py
from Project import *
v = open("Project.py", "w")
w = open("Backup.txt", "w")
PInput = None
DisableCode = "Save"
LineSeek = 0
Line = "None"
while PInput != DisableCode:
PInput = input(": ")
if PInput == "Create Line":
Line = input("Type in the command: ")
Line = repr(Line)
v.write(Line + "\n")
w.write(Line + "\n")
print("Done!")
After running the code
in Project.py...
'print("Hi")'
It must be
print("Hi")
What should i do change in PyPython.py to get rid of string marks in Project.py?
There is no need for repr(Line) here. The repr() method returns a string containing a printable representation of an object.
Try removing that line, it will work as expected.

How do I split text from a text file at newlines?

I need to encrypt a message. The message follows, it is saved in a file named assignmenttest.txt
Hi my name is Allie
I am a Junior
I like to play volleyball
I need the program to encrypt each line and keep it's format so that So, I wrote the following program:
fileInputName = input("Enter the file you want to encrypt: ")
key = int(input("Enter your shift key: "))
outputFileName = input("Enter the file name to write to: ")
fileInputOpen = open(fileInputName, "r")
message = fileInputOpen.read()
alphabet = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
shiftedStart = alphabet[len(alphabet) - key:]
shiftedEnd = alphabet[:len(alphabet) - key]
shiftedAlphabet = shiftedStart + shiftedEnd
encryptedMessage = ""
for character in message:
letterIndex = message.split("\n")
letterIndex = alphabet.find(character)
encryptedCharacter = shiftedAlphabet[letterIndex]
#print( "{0} -> {1}".format(character, encryptedCharacter))
encryptedMessage += encryptedCharacter
print("The encrypted message is: {0}".format(encryptedMessage))
outputFile = open( outputFileName, "w")
print(encryptedMessage, file=outputFile)
outputFile.close()
print("Done writing encrypted message to file {0}".format(outputFileName))
I tried to use a split at \n, but the output is not formatted in three separate lines, instead it is all just one long string of encrypted letters.
Any ideas on how to split the encrypted message at the correct spot and have it display as such? I've tried multiple split methods and none have worked. Thank you so much.
As the other answers have said, you can replace
fileInputOpen = open(fileInputName, "r")
message = fileInputOpen.read()
with
with open(fileInputName, "r") as f:
messages = f.readlines()
This way, messages will be a list of strings, where each string is the text from a single line in your input file. Then, with some slight modifications to your loop over each character in messages, you can encrypt each string from your messages list. Here, I replaced your encryptedMessage with currentEncryptedMessage and added encryptedMessages, a list that keeps track of the encrypted version of each string in messages.
encryptedMessages = []
currentEncryptedMessage = ""
for message in messages:
for character in message:
... # same as code provided
currentEncryptedMessage += encryptedCharacter
encryptedMessages.append(currentEncryptedMessage)
When writing to your file, you can iterate through each element in encryptedMessages to print line-by-line.
with open( outputFileName, "w") as outputFile:
for message in encryptedMessages:
print(message, file=outputFile)
And so your output text file will preserve the line breaks from your input file.
Instead of splitting at '\n', you can append all the characters in message that are not in alphabet to encryptedMessage when you encounter one.
for character in message:
if !(character in alphabet):
encryptedMessage += character
continue # this takes back to begin of the loop
letterIndex = alphabet.find(character)
encryptedCharacter = shiftedAlphabet[letterIndex]
#print( "{0} -> {1}".format(character, encryptedCharacter))
encryptedMessage += encryptedCharacter
Try changing:
message = fileInputOpen.read()
to
message = fileInputOpen.readlines()
This will make your file reads handle the file line by line. This will allow you to do your processing on a line by line basis first. Beyond that, If you want to encrypt each character, you'll need another for loop for the characters.
Instead of reading the file all at once. Read the lines individually.
f = open("file.txt")
for i in f.readlines():
print (i)
You'll have to loop each line and every character you want to
un-shift;
The script should only un-shift characters present in alphabet;
Checking for file existence is also a must or you may get errors if it doesn't exist.
with open... is the recommended way of reading and writing files in python.
Here's an approach:
import os
import string
fileInputName = input("Enter the file you want to encrypt: ")
while not os.path.exists(fileInputName):
fileInputName = input("{} file doesn't exist.\nEnter the file you want to encrypt : ".format(fileInputName))
key = int(input("Enter your shift key (> 0): "))
while key < 1 :
key = int(input("Invalid shift key value ({}) \nEnter your shift key (> 0): ".format(key)))
fileOutputName = input("Enter the file name to write to: ")
if os.path.exists(fileOutputName) :
ow = input("{} exists, overwrite? (y/n): ".format(fileOutputName))
if not ow.startswith("y"):
fileOutputName = input("Enter the file name to write to: ") # asks for output filename again
alphabet = string.ascii_letters + " "
shiftedStart = alphabet[len(alphabet) - key:]
shiftedEnd = alphabet[:len(alphabet) - key]
shiftedAlphabet = shiftedStart + shiftedEnd
with open(fileOutputName, "a") as outputFile: # opens out file
with open(fileInputName, "r") as inFile: # opens in file
for line in inFile.readlines(): # loop all lines in fileInput
encryptedCharacter = ""
for character in line: # loop all characters in line
if character in alphabet: # un-shift only if character is present in `alphabet`
letterIndex = alphabet.find(character)
encryptedCharacter += shiftedAlphabet[letterIndex]
else:
encryptedCharacter += character # add the original character un-shifted
outputFile.write("{}".format(encryptedCharacter)) # append line to outfile

Encryption with input and output file

I am new to python and am stuck on the task below. Below is an example of my input file and what I want it to output.
Input File Message (from online sample)
So pure of heart
And strong of mind
So true of aim with his marshmallow laser
Marshmallow laser
Output File Message
LhtinkXthYtaXTkm
ugWtlmkhgZthYtfbgW
LhtmknXthYtTbftpbmatabltfTklafTeehpteTlXk
FTklafTeehpteTlXk
Below is my syntax and guidance as to why it isn't completing the task intended would be helpful. It is printing 'wwww'....I believe it is a 'w' for each line.
inputFileName = input("Enter the message to encrypt: ")
key = int( input("Enter the shift key: " ))
outputFileName = input("Enter the output file name: " )
infile=open(inputFileName,"r")
outfile = open( outputFileName, "w" )
sequence=infile.readlines()
alphabet = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
shiftedAlphabetStart = alphabet[len(alphabet) - key:]
shiftedAlphabetEnd = alphabet[:len(alphabet) - key]
shiftedAlphabet = shiftedAlphabetStart + shiftedAlphabetEnd
print( alphabet )
print( shiftedAlphabet )
encryptedMessage = ''
for character in sequence:
letterIndex = alphabet.find( character )
encryptedCharacter = shiftedAlphabet[letterIndex]
#print( "{0} -> {1}".format( character, encryptedCharacter ) )
encryptedMessage = encryptedMessage + encryptedCharacter
print( "The encrypted message is: {0}".format( encryptedMessage ))
If you print(sequence), you'll realize that it's a List of lines, not a string.
So when you iterate through it with for character in sequence:, you're not iterating through the original text character by character, you're iterating through the list line by line.
This is because readlines() return a list of lines.
You can, if you still want to use readlines(), try adding something like:
original_text = ''
for line in sequence:
original_text += line
A better way however, is to simply change sequence = infile.readlines() to sequence = infile.read().

How can i add the functions try/except in this code?

I'm still creating this code where via a dictionary attack i find a password, inserted by the user. However I would insert some controls in the input of the file's source (ex. when I type the source of a file that doesn't exist) and when I open a file but inside there isn't a word that match with the password typed by the user. My mind tell me that I can use istructions as "If, Else, Elif" but other programmers tell me that i could use the try except instructions.
This is the code:
"""
This Code takes as input a password entered by the user and attempts a dictionary attack on the password.
"""
def dictionary_attack(pass_to_be_hacked, source_file):
try:
txt_file = open(source_file , "r")
for line in txt_file:
new_line = line.strip('\n')
if new_line == pass_to_be_hacked:
print "\nThe password that you typed is : " + new_line + "\n"
except(
print "Please, type a password: "
password_target = raw_input()
print "\nGood, now type the source of the file containing the words used for the attack: "
source_file = raw_input("\n")
dictionary_attack(password_target, source_file)
You can put this as your "File does not exist" exception and after you open the existing file you can but an if statement to check if anything exist inside the file in your way:
"""
This Code takes as input a password entered by the user and attempts a dictionary attack on the password.
"""
def dictionary_attack(pass_to_be_hacked, source_file):
try:
txt_file = open(source_file , "r")
if os.stat( txt_file).st_size > 0: #check if file is empty
for line in txt_file:
new_line = line.strip('\n')
if new_line == pass_to_be_hacked:
print("\nThe password that you typed is : " + new_line + "\n")
else:
print "Empty file!"
except IOError:
print "Error: File not found!"
print "Please, type a password: "
password_target = raw_input()
print "\nGood, now type the source of the file containing the words used for the attack: "
source_file = raw_input("\n")
dictionary_attack(password_target, source_file)

Unable to execute the else part of the if in the last line

When string is matched to the index without the else block in the if statment code works as expected.
But when else part is added it always displays "No string"
import sys
def string_search_index():
'''
This function search a string in a file through index and gives the result.
'''
if len(sys.argv) != 3:
print "Enter Two Arguments Only"
sys.exit(1)
stringsrch = sys.argv[2]
#size = len(sys.argv)
file_name = open("passwd", "r")
#print "No of Argu ", size
if sys.argv[1].isdigit():
fieldindex = int(sys.argv[1])-1
else:
print "Enter Integer in 1st Argument"
sys.exit(1)
fieldindex = int(sys.argv[1])-1
for store_file in file_name:
temp = store_file.split(":")
search = temp[fieldindex]
#print search
if stringsrch in search:
print store_file
else:
print "No String"
sys.exit(1)
string_search_index()
The string not found test should be outside the for loop:
file = open("my_file", "r")
string_found = False
# Loop over the lines of the file
for line in file:
temp = line.split(":")
if test_string in temp[index]:
print('Found it : {}'.format(line))
string_found = True
# String not found case
if not string_found:
print("String not found")

Categories

Resources