Skip to content

Commit a626ecf

Browse files
committed
Added File Handling - Exercise
1 parent ced5a69 commit a626ecf

File tree

14 files changed

+294
-0
lines changed

14 files changed

+294
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
def read_text():
2+
3+
try:
4+
5+
file = open("text.txt", "r")
6+
lines = [line for line in file] # Getting every line on different index
7+
file.close()
8+
return lines
9+
10+
except FileNotFoundError:
11+
raise FileNotFoundError("File not found")
12+
13+
14+
def get_even_lines(text):
15+
even_lines = []
16+
for line in range(len(text)):
17+
if line % 2 == 0:
18+
even_lines.append(text[line]) # getting only the lines at even indexes
19+
return even_lines
20+
21+
22+
def change_symbol(text):
23+
change_symbols = {"-", ",", ".", "!", "?"} # symbols that must be changed to @
24+
25+
for line in range(len(text)):
26+
for char in range(len(text[line])):
27+
if text[line][char] in change_symbols:
28+
text[line] = text[line][0:char] + '@' + text[line][char+1:]
29+
30+
31+
def print_result(text):
32+
for line in text:
33+
sentence = line.split()[::-1] # reversing the result, without reversing the words.
34+
# Example:
35+
# >>> line = 'some text'
36+
# >>> line[::-1] -> 'txet emos'
37+
# >>> line.split()[::-1] -> ['text', 'some']
38+
# >>> ' '.join(line) -> 'text some'
39+
print(' '.join(sentence))
40+
41+
42+
text = read_text()
43+
even_lines = get_even_lines(text)
44+
45+
if __name__ == '__main__':
46+
change_symbol(even_lines)
47+
print_result(even_lines)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
-I was quick to judge him, but it wasn't his fault.
2+
-Is this some kind of joke?! Is it?
3+
-Quick, hide here. It is safer.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
def read_text():
2+
3+
try:
4+
5+
file = open("text.txt", "r")
6+
lines = [line for line in file] # getting every line from the text
7+
file.close()
8+
9+
except FileNotFoundError:
10+
raise FileNotFoundError("File not found")
11+
12+
for line in range(len(lines)):
13+
14+
letters = 0
15+
punctuation_marks = 0
16+
17+
for character in range(len(lines[line])):
18+
19+
char = lines[line][character]
20+
21+
if 65 <= ord(char) <= 90 or 97 <= ord(char) <= 122: # if char is letter
22+
letters += 1
23+
24+
elif 33 <= ord(char) <= 47 or 58 <= ord(char) <= 64: # if char is punctuation mark
25+
punctuation_marks += 1
26+
27+
if lines[line][-1] == '\n': # if the sentence ends with '\n' which stands for new line.
28+
lines[line] = lines[line][:-1] # We remove it, because otherwise it would give us wrong output
29+
30+
lines[line] = f"Line {line+1}: {lines[line]} ({letters})({punctuation_marks})\n"
31+
32+
return lines
33+
34+
35+
def output_txt(text):
36+
37+
file = open("output.txt", "w") # create for writing
38+
[file.write(line) for line in text] # write the output in
39+
file.close() # close for writing
40+
41+
file = open("output.txt", "r") # open for reading
42+
output = ''.join([line for line in file]) # read every line from the text
43+
file.close() # close file for reading
44+
45+
return output
46+
47+
48+
text = read_text()
49+
print(output_txt(text))
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
-I was quick to judge him, but it wasn't his fault.
2+
-Is this some kind of joke?! Is it?
3+
-Quick, hide here. It is safer.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
import os
2+
import time
3+
4+
5+
def create_file(file_name, *args): # *args is in case we receive more than one parameter
6+
try:
7+
''' Delete file content '''
8+
9+
os.remove(file_name) # removing file
10+
file = open(file_name, "x") # creating file
11+
file.close() # closing file
12+
print(f"File {file_name} content was deleted") # comment that will show on the console if the content is deleted
13+
14+
except FileNotFoundError:
15+
''' Create file '''
16+
17+
file = open(file_name, "x") # creating file
18+
file.close() # closing file
19+
print(f"File {file_name} was created") # comment, that will show on the console, if the creation was successful
20+
21+
22+
def add_content(file_name, *args_content): # *args_content is in case we receive more than two parameters
23+
content = args_content[0]
24+
25+
if os.path.exists(file_name):
26+
print(f"Content added to {file_name}") # comment that will show on the console if the file exists
27+
28+
else:
29+
print(f"Created {file_name} and added content") # comment that will show, if the file does not exist
30+
31+
file = open(file_name, "a+") # open file if it exists, else it creates the file.
32+
file.write(f"{content}\n") # adding the content
33+
file.close() # closing file
34+
35+
36+
def replace_content(file_name, *content): # *content is in case we receive more than two parameters
37+
old_content, new_content, = content[0], content[1]
38+
39+
try:
40+
41+
file = open(file_name, "r") # open for reading
42+
lines = [line for line in file] # read lines
43+
file.close() # close for reading
44+
45+
for index, line in enumerate(lines):
46+
line = line.replace(old_content, new_content) # replace all occurrences
47+
lines[index] = line
48+
49+
os.remove(file_name) # remove file
50+
file = open(file_name, "x") # create file (delete content)
51+
file.close() # close file
52+
53+
file = open(file_name, "a+") # open for writing
54+
[file.write(line) for line in lines] # rewrite the modified content
55+
file.close() # close for writing
56+
57+
print(f"{file_name}'s content successfully changed") # if everything is successful, this will show on the console
58+
59+
except FileNotFoundError:
60+
print("An error occurred", "# replacing content")
61+
62+
63+
def delete_file(file_name, *args): # *args is in case we receive more than one parameter
64+
if os.path.exists(file_name):
65+
os.remove(file_name)
66+
print(f"File {file_name} was removed") # this will show on the console, if the file is removed successfully
67+
else:
68+
print("An error occurred", "# Cannot delete file that does not exist") # If the file does not exists
69+
70+
71+
operations = {
72+
"Create": create_file,
73+
"Add": add_content,
74+
"Replace": replace_content,
75+
"Delete": delete_file
76+
}
77+
78+
command = input()
79+
while command != "End":
80+
81+
operation, name_of_file, *more_content = command.split("-")
82+
83+
operations[operation](name_of_file, *more_content)
84+
85+
time.sleep(0.1) # using time.sleep, so the output will be ordered, otherwise it somehow gets mixed up
86+
87+
command = input()
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import os
2+
3+
4+
def get_files():
5+
6+
if os.path.exists("directory/report.txt"): # Making sure, on second run, the report won't count itself
7+
os.remove("directory/report.txt")
8+
9+
if os.path.exists("report.txt"): # Making sure, on second run, the report won't count itself
10+
os.remove("report.txt")
11+
12+
path = "directory" # path
13+
files = os.listdir(path) # files in path/directory
14+
15+
return files
16+
17+
18+
def sort_files(files):
19+
20+
# sort files and extensions
21+
extensions = set()
22+
for file_extension in files:
23+
extension = file_extension.split(".")[-1] # extension. Example: html
24+
extensions.add(f".{extension}") # extension with dot. Example: .html
25+
26+
sorted_files = sorted(files) # -> list
27+
sorted_extensions = sorted(extensions) # -> list
28+
29+
# create report.txt
30+
file1 = open("report.txt", "a+") # creating report 1
31+
file2 = open("directory/report.txt", "a+") # creating report 2
32+
33+
# combine file with extension
34+
for extension in sorted_extensions:
35+
file1.write(f"{extension}\n")
36+
file2.write(f"{extension}\n")
37+
38+
for file in sorted_files:
39+
if extension in file:
40+
file1.write(f"- - - {file}\n")
41+
file2.write(f"- - - {file}\n")
42+
43+
# closing opened files
44+
file1.close()
45+
file2.close()
46+
47+
return "The result from the program is saved in report.txt"
48+
49+
50+
files = get_files()
51+
print(sort_files(files))

Advanced/5.File Handling/File Handling - Exercise/04. Directory Traversal/directory/demo.pptx

Whitespace-only changes.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
<title>You're in my world now</title>
6+
<script src="index.js"></script>
7+
</head>
8+
<body>
9+
<div class="test">
10+
<h1 onclick="ChangeColor();" id="main" style="font-size: 250px; text-align: center">Click Me</h1>
11+
</div>
12+
</body>
13+
</html>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
function ChangeColor() {
2+
document.getElementById("main").style.color = "purple";
3+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
log _> pip install ME
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
"HEllO WORLD!"
2+
print("Please give me good grade!")
3+
print("Love <3 :)")
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# create a directory with files
2+
3+
2nd. # Make code :)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
print("I'm a Python Program")
2+
print("It's nice to meet you!")
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
from collections import deque
2+
from time import sleep
3+
4+
rows, columns = 10, 3
5+
snake = "Python"
6+
7+
while True:
8+
9+
index_snake = 0
10+
11+
for row in range(rows):
12+
13+
result = deque()
14+
15+
for col in range(columns):
16+
17+
if index_snake == len(snake):
18+
index_snake = 0
19+
20+
if row % 2 == 0:
21+
result.append(snake[index_snake])
22+
23+
else:
24+
result.appendleft(snake[index_snake])
25+
26+
index_snake += 1
27+
28+
print("".join(result))
29+
sleep(0.1)

0 commit comments

Comments
 (0)