I am writing a program that encrypts files and decrypts them with a key. Code:
import random, os, time
#Collecting all files
pad = r'C:\Users\Hugo\Desktop\Malware\Test'
bestand_list = []
for files in next(os.walk(pad))[2]:
bestand_list.append(pad + '\\' + files)
#Random 10 characters making encryption
s = 'abcdefghijklmnopqrstuvxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&'
sleutel = ''
for i in range(10):
sleutel += random.choice(s)
print(sleutel)
print('The computer is being encrypted')
time.sleep(1)
def Decrypt():
x = 0
decryptie = input('Enter your decryption code: \n')
if (decryptie == sleutel):
for bestand in bestand_list:
for bestand_naam in bestandnaam_list:
locatie = bestand_list[x]
os.rename(bestand_naam, locatie)
x += 1
print ('Your file will now be decrypted')
else:
print ('Unfortunately your file was not decrypted')
def Encrypt():
x = 0
global bestandnaam_list
bestandnaam_list = []
for bestand in bestand_list:
bestand_naam = ''
locatie = bestand_list[x]
for i in range (10):
bestand_naam += random.choice(s)
bestandnaam_list.append(pad + '\\' + bestand_naam)
os.rename(locatie, pad + '\\' + bestand_naam)
x += 1
print('Your files are now encrypted')
Decrypt()
Encrypt()
The problem that I am having is that the second file gets renamed to the first file by decryption. This results in a FileExistError. There is probably something wrong with the:
x += 1
in def Decrypt()
How to fix this issue?
Edit: Full traceback:
Traceback(most recent call last):
File "crypto.py", line 29, in Decrypt
os.rename(bestand_naam, locatie)
FileExistsError: [WinError 183] Cannot make a file that already exists.
You had multiple problems in your code.
def Decrypt():
x = 0
decryptie = input('Enter your decryption code: \n')
if (decryptie == sleutel):
for bestand in bestand_list:
os.rename(bestandnaam_list[x], bestand)
x += 1
print ('Your file will now be decrypted')
else:
print ('Unfortunately your file was not decrypted')
This should do the trick.
Btw when you submit your code please DO PRINT what you are doing, for you and for us and DO use english varnames since i have no clue on what sleutel and other variables names means.
You were doing 2 forloops that was giving wrong and multiples filenames/paths to os.rename .
Forgot to add this,
in def Encrypt you call directly Decrypt, move it to the end of the file.
Like so:
Encrypt()
Decrypt()
Related
I tried to extract data from a text file (cisco switch logs) and convert it to CSV so I can create a table and sort out the data & create graphs out of it. So here is my code:
import pandas as pd
import csv
import time
from datetime import datetime
import os
import glob
import sys
pathh = glob.glob("C:\\Users\\Taffy R. Mantang\\Desktop\\PR logs\\*\\")
#This part of the code opens all the text with the name ISW-1.txt inside the PR logs folder
for x in pathh:
# Detect the line number in text file to know where the row begin
phrase = "Shelf Panel CPUID Power CPU(5s) CPU(1m) CPU(5m) Peak PhyMem FreeMem Mem"
file = open("{0}".format(x) + "\\ISW-1.txt")
for number, line in enumerate(file):
if phrase in line:
sh_pro = number
break
file.close()
#Convert the text file to CSV from the row determined earlier
with open("{0}".format(x) + '\\ISW-1.txt', 'r') as rf:
r = csv.reader(rf, skipinitialspace=True, delimiter=' ')
rows = list(r)
heada = rows[sh_pro]
heada.insert(0, " ")
print(heada)
#to mark the last row
skipprocessor = sh_pro + 4
for i in range(7):
if i == 0:
print(rows[skipprocessor + i])
if i == 2:
sub_heada = rows[skipprocessor + i]
sub_heada.insert(0, " ")
sub_heada.insert(1, " ")
sub_heada.insert(2, " ")
print(rows[skipprocessor + i])
if i == 4:
sub_heada = rows[skipprocessor + i]
sub_heada.insert(0, " ")
sub_heada.insert(1, " ")
sub_heada.insert(2, " ")
print(rows[skipprocessor + i])
if i == 6:
sub_heada = rows[skipprocessor + i]
sub_heada.insert(0, " ")
sub_heada.insert(1, " ")
sub_heada.insert(2, " ")
print(rows[skipprocessor + i])
Previously it worked and it printed the output successfully. However while I was experimenting with exporting the output to an excel table, suddenly there was an error saying:
Traceback (most recent call last):
File "C:\Users\Taffy R. Mantang\PycharmProjects\pythonProject\main.py", line 26, in
heada = rows[sh_pro]
NameError: name 'sh_pro' is not defined
I traced back and undo everything but it still gives the same error.
I tried to remove an indent on line 26, it managed to print(heada). but messed up the if else code down below it and not print out the rest below.
What exactly is the problem? Help :'''((
sh_pro is not defined because you are not hitting the condition if phrase in line:, I would suggest:
for number, line in enumerate(file):
if phrase in line:
sh_pro = number
break
file.close()
#Convert the text file to CSV from the row determined earlier
with open("{0}".format(x) + '\\ISW-1.txt', 'r') as rf:
r = csv.reader(rf, skipinitialspace=True, delimiter=' ')
rows = list(r)
try:
heada = rows[sh_pro]
except NameError:
# error handling
In order to declare sh_pro, the condition if phrase in line: in your for cycle should return True. So if your condition returns False then your interpreter never meets such name as sh_pro. You can try to modify your code in a way that sh_pro is declared before you want to start working with it.
for number, line in enumerate(file):
if phrase in line:
sh_pro = number
break
file.close()
I have a program where I encrypt class.__dict__ and save it to a file in an array so the file looks something like this -
{'some name':[1, 2, 3],
'data':'''9ÈX§Ë¡¡Ö© îo[ y^5Ð¥"¢§«!fa¥mc^W''' #somthing like this but a lot longer
}
I then read it and need to decrypt data but before that, I need to get the data from the array that is currently a string which I did with eval(fileContent) and it gives me the error -
Traceback (most recent call last):
File "C:/Users/stemb/Documents/programing/python/programs/img editor/__init__.py", line 127, in
<module>
main()
File "C:/Users/stemb/Documents/programing/python/programs/img editor/__init__.py", line 102, in main
save_code.auto_save_load()
File "C:\Users\stemb\Documents\programing\python\programs\img editor\save_code.py", line 153, in
auto_save_load
data = eval(fileContent)
ValueError: source code string cannot contain null bytes
My reading function is this
data = open("./save." + GLOBAL.fileType, "r", encoding="utf-8").read()
json.loads gives json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
My code is -
# imports
import json
import random
import time
print("Finished save_progress imports")
def encrypt(obj, log=0): #encrypt
# set data
data = str(obj.__dict__)
key = "codeAsciEightAndMabyA_Seven" + str(time.time()) # crate key
key = list(key)
random.shuffle(key) # randomize key
cryptionKeys = list()
encrypted = list()
iMinus = 0
for i in range(len(data)): # create a random + or - for extra security
cryptionKeys.append(random.choice(("+", "-")))
# encode part
for i, c in enumerate(data):
# set individual data
charAsci = ord(c)
cryptionKey = cryptionKeys[i]
done = 0
while done == 0:
try:
charKey = ord(key[i - iMinus])
done = 1
except IndexError:
iMinus += len(key)
if cryptionKey == "+":
encryptedOrd = charAsci + charKey
else:
encryptedOrd = charAsci - charKey
if encryptedOrd < 0:
encryptedOrd += 110000
cryptionKeys[i] = "="
cryptionKey = cryptionKeys[i]
encryptedChar = chr(encryptedOrd)
encrypted.append(encryptedChar)
if log == 1:
print("charNumb \/")
print(i)
print("charAsci \/")
print(charAsci)
print("cryptionKey \/")
print(cryptionKey)
print("charKey \/")
print(charKey)
print("encryptedOrd \/")
print(encryptedOrd)
print("encryptedChar \/")
print(encryptedChar)
print()
encrypted2 = encrypted
encrypted = ""
for c in encrypted2:
encrypted += c
return str(encrypted), str(key), str(cryptionKeys)
def auto_save(GLOBAL): # the save func
file = open("./save." + GLOBAL.fileType, "w", encoding="utf-8")
encryptedGLOBAL, key, cryptionKeys = encrypt(GLOBAL)
out = ("{'key':" + str(key) + ", 'cryptionKeys':" + str(cryptionKeys) + ", 'data':'''" + str(
encryptedGLOBAL) + "'''}")
print(out)
file.write(out)
file.close()
def auto_save_load(aclass): # the loading dunc
data = open("./save." + GLOBAL.fileType, "r", encoding="utf-8").read()
data = eval(data)
key = data["key"]
cryptionKeys = data["cryptionKeys"]
encryptedGLOBAL = data["data"]
print(key)
print()
print(cryptionKeys)
print()
print(encryptedGLOBAL)
Other answers have said to remove the null bytes but the encryption method needs them.
Please help.
I have 50 files in a directory that are suppose to compare with one file, e.g., original.txt. I have the following code. It works well when I give the file name one-by-one, manually. I want to automate it for this I used 'glob.blog'
folder = "files/"
path = '*.rbd'
path = folder + path
files=sorted(glob.glob(path))
Here the complete code:
import glob
from itertools import islice
import linecache
num_lines_nonbram = 1891427
bits_perline = 32
total_bit_flips = 0
num_bit_diff_flip_zero = 0
num_bit_diff_flip_ones = 0
folder = "files/"
path = '*.rbd'
path = folder + path
files=sorted(glob.glob(path))
original=open('files/mull-original-readback.rbd','r')
#source1 = open(file1, "r")
for filename in files:
del_lines = 101
with open(filename,'r') as f:
i=1
while i <= del_lines:
line1 = f.readline()
lineoriginal=original.readline()
i+=1
i=0
num_bit_diff_flip_zero = 0
num_bit_diff_flip_ones = 0
num_lines_diff =0
i=0
j=0
k=0
a_write2 = ""
while i < (num_lines_nonbram-del_lines):
line1 = f.readline()
lineoriginal = original.readline()
while k < bits_perline:
if ((lineoriginal[k] == line1[k])):
a_write2 += " "
else:
if (lineoriginal[k]=="0"):
#if ((line1[k]=="0" and line1[k]=="1")):
num_bit_diff_flip_zero += 1
if (lineoriginal[k]=="1"):
#if ((line1[k]=="0" and line1[k]=="1")):
num_bit_diff_flip_ones += 1
#if ((line1[k]==1 and line1[k]==0)):
#a_write_file2 = str(i+1) + " " + str(31-k) + "\n" + a_write_file2
#a_write2 += "^"
#num_bit_diff_flip_one += 1
# else:
# a_write2 += " "
k+=1
total_bit_flips=num_bit_diff_flip_zero+num_bit_diff_flip_ones
i+=1
k=0
i = 0
print files
print "Number of bits flip zero= %d" %num_bit_diff_flip_zero +"\n" +"Number of bits flip one= %d" %num_bit_diff_flip_ones +"\n" "Total bit flips = %d " %total_bit_flips
f.close()
original.close()
I got the error:
Traceback (most recent call last):
File "random-ones-zeros.py", line 65, in <module>
if ((lineoriginal[k] == line1[k])):
IndexError: string index out of range
I guess there is some issue with the reading the file automatically, instead giving name manually. But, didn't able to find the solution.
For this the string index is out of range because the value k is iterated once more than intended so the value of the variable exceeds the scope of the program. This should be able to be fixed by using substituting it to
if ((lineoriginal[k-1] == line1[k-1])):
Hope this helps, but I can't access Python right now so I can't test it out :-)
This is my code to opening the file; I would like it to contain a name and a figure:
file_n = "Class_" + str(num_class) + ".txt"
file = open(file_n,"r")
string = file.read()
file.close()
and this is the error message I keep getting and I can't work out how to fix it:
file = open(file_n,"r")
IOError: [Errno 2] No such file or directory: 'Class_2.txt'
Could someone please tell me why this happening and the solution to it?
im still very confused
this is my whole code:
import random
import json
score = 0
turn = 1
turn = turn + 1
name = raw_input("what is your name?")
num_class = input("What class are you in? (1,2,3)")
print ("hello "+name+" have fun and good luck!")
for turn in range(10):
randnum_1 = random.randint(1,10)
randnum_2 = random.randint(1,10)
operators = ["+", "-", "*"]
operator_picked = operators[random.randint(0,2)]
human_answer = raw_input("What is " + str(randnum_1) +" "+ operator_picked +" " + str(randnum_2) + "?")
correct_answer = str((eval(str(randnum_1) + operator_picked + str(randnum_2))))
if correct_answer == human_answer :
score = score+1
print ("Correct!")
else:
print ("Incorrect!" +"The correct answer is " + str(correct_answer))
print("\nYour score was " + str(score)+ "/10")
file_name = ("Class_" + str(num_class) + ".txt")
file = open(file_n,"r")
string = file.read()
file.close()
dict = {}
Like Kevin and Flavian mentioned the directory of Class_2.txt is most likely not the directory where your script is located.
file_n = "/ActualDirectory/ofFile/Class_" + str(num_class) + ".txt"
Make sure that your Python code lies in the same directory with your txt file.
So it should be like this:
Of course the two files can be in different directories, but then you should provide the relevant, or absolute, path of the txt file to your code.
As 1001010 stated, you could check your current directory by doing:
import os
print(os.getcwd())
I want to extract 2 parts from 4 voice krn score and save them as a midi file.
I can load the files:
s = converter.parse('/something.krn')
I can get some basic info like this:
s.metadata.title
In v2, I want to store the part of s that has a label "Cantus". Any idea how to check for a label? They have a label in krn.
Once I have the number of the part, I can get it with
s.parts[i]
The krn file is defined like this:
**kern **kern **kern **kern **kern
*Ibass *Itenor *Itenor *Icalto *Icant
!Bassus !Tenor 2 !Tenor 1 !Altus !Cantus
I am guessing labels is not the correct name, as I can't find this in music21 documentation, perhaps the name of the part?
I can't seem to find the property in the music21 documentation.
I was finally able to do it this way:
import sys
from music21 import *
import os
# input ("Please make sure that you have places all the krn files in a subdirectory called data. Press enter to continue")
for filename in os.listdir('./data'):
s = converter.parse('./data/' + filename)
sys.stdout.write('Processing ' + filename + '... ')
numcant = -1
nums = list()
try:
length = len(s.parts)
except:
length = 0
if (length > 0):
for num in range(0,length):
# sys.stdout.write(s.parts[num].flat.getElementsByClass('SpineComment')[0].comment + ' - ')
if (s.parts[num].flat.getElementsByClass('SpineComment')[0].comment == "Cantus"):
numcant = num
# print "cant "
# print numcant
else:
# print "nums"
nums.append(num)
# print num
else:
# sys.stdout.write(' - no parts present.')
sys.stdout.write('\n')
try:
length = len(nums)
except:
length = 0
if (length > 0):
sys.stdout.write('\n')
if (numcant != -1):
for num in nums:
sys.stdout.write(' - ' + filename[:-4] + '_' + str(num) + '.mid written.\n')
# print "cantus present"
s2 = stream.Stream()
s2.insert(0, s.parts[num])
s2.insert(0, s.parts[numcant])
# write the midi file
s2.write('midi', './midi/' + filename[:-4] + '_' + str(num) + '.mid')
# sys.stdout.write('I')
else:
sys.stdout.write(' - no cantus specified for this file.\n')
else:
sys.stdout.write(' - not enough parts in this file.\n')
sys.stdout.write('\n')