Skip to content

Commit e0fc981

Browse files
committed
Merge branch 'main' of https://github.com/larymak/Python-project-Scripts into main
2 parents 63085ee + 8bdc5a5 commit e0fc981

File tree

12 files changed

+1306
-1
lines changed

12 files changed

+1306
-1
lines changed

CSV_files/README.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# Reading and Writing a CSV File
2+
* There are various ways to read a CSV file that uses either the CSV module or the pandas library.
3+
4+
- csv Module: The CSV module is one of the modules in Python which provides classes for reading and writing tabular information in CSV file format.
5+
6+
- pandas Library: The pandas library is one of the open-source Python libraries that provide high-performance, convenient data structures and data analysis tools and techniques for Python programming.
7+
8+
* **Read using csv.DictReader() class:** the CSV file is first opened using the open() method then it is read by using the DictReader class of csv module which works like a regular reader but maps the information in the CSV file into a dictionary. The very first line of the file consists of dictionary keys.
9+
* **Read using pandas module** : you can read cvs file using pandas ,using read_csv method , you can also determine if you want to read the head or the tail or read specific piece of data .
10+
11+
12+
* There are various classes provide by csv module for writting to csv:
13+
- using csv.writer class
14+
- using csv.DictWritter class
15+
16+
* **Write using cvs.DictWritter() class**: this class returns a writer object which maps directories onto output rows.
17+
18+
19+
* **Write using pandas module**:You can save your Pandas DataFrame as a CSV file with .to_csv(data)
20+
21+
22+
23+
24+
25+
# Steps :
26+
27+
1- clone the repo
28+
29+
2- poetry install
30+
31+
3- poetry shell
32+
33+
4- run the wanted file

CSV_files/assets/addresses.csv

Whitespace-only changes.

CSV_files/assets/course_name.csv

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
name,course
2+
Noura,python40python401
3+
Mahmoud,python401
4+
Nizar,python401
5+
Raneem,python401
6+
Omer,python401

CSV_files/read_csv.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import csv
2+
import pandas as pd
3+
4+
def read_using_DictReader(path):
5+
# opening the CSV file
6+
with open(path, mode ='r') as file:
7+
# reading the CSV file
8+
csvFile = csv.DictReader(file)
9+
10+
# displaying the contents of the CSV file
11+
for lines in csvFile:
12+
return lines
13+
14+
def read_by_pandas_head():
15+
data=pd.read_csv('CSV_files/assets/addresses.csv')
16+
return data.head()
17+
18+
def read_by_pandas_tail():
19+
data=pd.read_csv('CSV_files/assets/addresses.csv')
20+
return data.tail()
21+
22+
if __name__=="__main__":
23+
print(read_using_DictReader('assets/addresses.csv'))
24+
print(read_using_DictReader())
25+
print(read_by_pandas_head())
26+
print(read_by_pandas_tail())
27+

CSV_files/write_csv.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import csv
2+
import pandas as pd
3+
4+
5+
6+
7+
def write_to_csv_files_using_DictWriter_class(data,fields,filename):
8+
9+
with open(filename, 'w') as csvfile:
10+
# creating a csv dict writer object
11+
writer = csv.DictWriter(csvfile, fieldnames = fields)
12+
13+
# writing headers (field names)
14+
writer.writeheader()
15+
16+
# writing data rows
17+
writer.writerows(data)
18+
19+
def write_by_pandas(name_dict):
20+
df = pd.DataFrame(name_dict)
21+
return df
22+
23+
if __name__=="__main__":
24+
# my data rows as dictionary objects
25+
mydata =[{'name': 'Noura', 'course': 'python40python401'},
26+
{'name': 'Mahmoud', 'course': 'python401'},
27+
{'name': 'Nizar', 'course': 'python401'},
28+
{'name': 'Raneem', 'course': 'python401'},
29+
{'name': 'Omer', 'course': 'python401'}, ]
30+
31+
# field names
32+
fields = ['name','course']
33+
34+
# name of csv file
35+
filename = "assets/course_name.csv"
36+
37+
# writing to csv file
38+
print(write_to_csv_files_using_DictWriter_class(mydata,fields,filename))
39+
40+
41+
name_dict = {
42+
'Name': ['Omar','Mahmoud','Noura','Raneem'],
43+
'Score': [82,86,84,65]
44+
}
45+
print(write_by_pandas(name_dict))

Compress Image/img_comp.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from PIL import Image
22

33
def compress_image(default_image=Image.open('original_image.jpg')):
4-
''' Takes an image file and compress it with losing image quality. '''
4+
''' Takes an image file and compress it without losing image quality. '''
55

66
''' If no image file is provided, the default image will be compressed '''
77

Compress Image/requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Pillow==8.2.0
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
#49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d
2+
#SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t
3+
########https://base64.guru/converter/encode/hex;
4+
hexalph = """!"#$%&'()*+,-./0123456789:'<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"""
5+
hexdecalph = '0123456789abcdef'
6+
finalascii = """ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"""
7+
fname = 'NEWtestoutput.txt'
8+
fhand = open(fname, 'w')
9+
fhand.close()
10+
fhand = open(fname, 'r+')
11+
#
12+
#
13+
#
14+
#below starts the function
15+
def hextodec(hexstring) :
16+
#initialize empty list to contain hex pairs
17+
hexlist = []
18+
#turn the input string into a list
19+
hexinput = list(hexstring)
20+
#loop through the list of characters and pair them up
21+
while len(hexinput) > 0 :
22+
#take first two characters, turn them into a string, assign them to a variable
23+
hexpair = ''.join(hexinput[:2])
24+
fhand.write(f'Parsed hex pair {hexpair}\n')
25+
#add the hex pair to the list
26+
hexlist.append(hexpair)
27+
#remove the first two characters from the original input string list
28+
hexinput = hexinput[2:]
29+
fhand.write(f'List of parsed hex pairs is {hexlist}\n')
30+
declist = []
31+
#going through each pair, organizing, and converting to decimal
32+
for pair in hexlist :
33+
#turn the pair into a list and change to lowercase to match hex character list above
34+
hextodecinput = list(pair.lower())
35+
fhand.write(f'Lowercase pair list is {hextodecinput}\n')
36+
#reverse the list to process from lowest priority to highest
37+
hextodecinput.reverse()
38+
fhand.write(f'Reversed list is {hextodecinput}\n')
39+
total = 0
40+
#loop through each character and convert from hexadecimal to decimal
41+
for char in hextodecinput :
42+
fhand.write(f'{hexdecalph.index(char)} is index of character in hexdecalph list\n')
43+
fhand.write(f'{hextodecinput.index(char)} is index of character in input\n')
44+
fhand.write(f'{16 ** hextodecinput.index(char)} is 16 to the power of the index of the character in the input\n')
45+
fhand.write(f'---Equation will be {hexdecalph.index(char)} * {16 ** hextodecinput.index(char)}\n')
46+
#do the actual hexadecimal conversion
47+
total += ((hexdecalph.index(char)) * (16 ** hextodecinput.index(char)))
48+
fhand.write(f'---Running total is {total}\n')
49+
#turn total into a string and append to list
50+
total = str(total)
51+
fhand.write(f'{total} is decimal conversion\n')
52+
declist.append(total)
53+
fhand.write(f'{declist} is list of decimal conversions\n')
54+
binlist = []
55+
#loop through each decimal in the list to convert to final base64 ASCII characters
56+
for dec in declist :
57+
#convert to integer
58+
dec2 = int(dec)
59+
#convert to binary, padding with leading zeros if necessary for 8 total characters
60+
decbin = f'{dec2:08b}'
61+
decbin = list(decbin)
62+
decbin = ''.join(decbin)
63+
fhand.write(f'{decbin} is binary conversion of decimal\n')
64+
binlist.append(decbin)
65+
binlist = ''.join(binlist)
66+
#to convert to base64, 6bit words are needed. this ensures the list is divisible by 6
67+
if not len(binlist) % 6 == 0 :
68+
binlist = list(binlist)
69+
binlist.append('00')
70+
binlist = ''.join(binlist)
71+
if not len(binlist) % 6 == 0 :
72+
binlist = list(binlist)
73+
binlist.append('00')
74+
binlist = ''.join(binlist)
75+
sixbitlist = []
76+
#loop through the list, separating bits out into words of 6
77+
while len(binlist) > 0 :
78+
binword = binlist[:6]
79+
binlist = binlist[6:]
80+
binword = ''.join(binword)
81+
fhand.write(f'Parsed 6-bit word {binword}\n')
82+
sixbitlist.append(binword)
83+
finaldeclist = []
84+
#loop through each 6-bit word in list, converting to decimal
85+
for item in sixbitlist :
86+
#convert the word to integer in base2
87+
newdec = int(item, 2)
88+
newdec = str(newdec)
89+
fhand.write(f'{newdec} is decimal conversion of 6-bit word {item}\n')
90+
finaldeclist.append(newdec)
91+
finalcharlist = []
92+
#loop through list of decimal conversions, converting to ASCII using the base64 conversion table
93+
for item in finaldeclist :
94+
finalchar = int(item)
95+
finalchar = finalascii[finalchar]
96+
finalchar = str(finalchar)
97+
fhand.write(f'{item} is decimal in list to convert using base64 table\n')
98+
fhand.write(f'{finalchar} is final character in base64 list using decimal conversion of 6-bit binary word as index\n')
99+
finalcharlist.append(finalchar)
100+
finalword = ''.join(finalcharlist)
101+
finalword = list(finalword)
102+
#base64 strings are divisible by 4, so the following three lines ensure that the string is padded with ending '=' if necessary
103+
if not len(finalword) % 4 == 0 :
104+
finalword.append('=')
105+
if not len(finalword) % 4 == 0 :
106+
finalword.append('=')
107+
if not len(finalword) % 4 == 0 :
108+
finalword.append('=')
109+
finalword = ''.join(finalword)
110+
fhand.write(f'{finalword} is base64 conversion of {hexstring}\n')
111+
return finalword
112+
print(hextodec(input('')))
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import os,sys
2+
currentdir=os.path.dirname(os.path.realpath(__file__))
3+
parentdir=os.path.dirname(currentdir)
4+
sys.path.append(parentdir)
5+
hda='0123456789abcdef';b64t="""ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"""
6+
fn=f'{currentdir}/log.txt';fh=open(fn,'w');fh.close();fh=open(fn,'r+')
7+
def hextodec(s):
8+
l,h=[],list(s)
9+
while len(h)>0:
10+
hp=''.join(h[:2]);fh.write(f'Parsed hex pair {hp}\n')
11+
l.append(hp);h=h[2:]
12+
fh.write(f'----List of parsed hex pairs is {l}\n')
13+
dl=[]
14+
for p in l:
15+
dcp=list(p.lower())
16+
fh.write(f'\tLowercase pair list is {dcp}\n')
17+
dcp.reverse()
18+
fh.write(f'\tReversed list is {dcp}\n')
19+
t=0
20+
for c in dcp:
21+
fh.write(f'\t\t{hda.index(c)} is index of character in hda list\n')
22+
fh.write(f'\t\t{dcp.index(c)} is index of character in input\n')
23+
fh.write(f'\t----{16**dcp.index(c)} is 16 to the power of the index of the character in the input\n')
24+
fh.write(f'----Equation will be {hda.index(c)}*{16**dcp.index(c)}\n')
25+
t+=((hda.index(c))*(16**dcp.index(c)))
26+
fh.write(f'----Running total is {t}\n')
27+
t=str(t)
28+
fh.write(f'\t\t----{t} is decimal conversion\n')
29+
dl.append(t)
30+
fh.write(f'____{dl} is list of decimal conversions\n')
31+
bl=[]
32+
for n in dl:
33+
bc=''.join(list(f'{int(n):08b}'))
34+
fh.write(f'{bc} is binary conversion of decimal\n')
35+
bl.append(bc)
36+
bl=''.join(bl)
37+
for i in range(2):
38+
if not len(bl)%6==0:
39+
bl=list(bl)
40+
bl.append('00')
41+
bl=''.join(bl)
42+
sb=[]
43+
while len(bl)>0:
44+
w,bl=bl[:6],bl[6:]
45+
w=''.join(w)
46+
fh.write(f'-Parsed 6-bit word {w}\n')
47+
sb.append(w)
48+
fdl=[]
49+
for i in sb:
50+
fd=str(int(i,2))
51+
fh.write(f'{fd}\tis decimal conversion of 6-bit word {i}\n')
52+
fdl.append(fd)
53+
fl=[]
54+
for i in fdl:
55+
c=str(b64t[int(i)])
56+
fh.write(f'\t{i} is decimal in list to convert using base64 table\n')
57+
fh.write(f'\t----{c} is final character in base64 list using decimal conversion of 6-bit binary word as index\n')
58+
fl.append(c)
59+
fw=list(''.join(fl))
60+
for i in range(3):
61+
if not len(fw)%4==0:fw.append('=')
62+
fw=''.join(fw)
63+
fh.write(f'{fw} is base64 conversion of {s}\n')
64+
return fw
65+
print(hextodec(input('')))

0 commit comments

Comments
 (0)