Created
January 23, 2021 17:27
-
-
Save mkojoa/1f8ae389f950370fa7d4f96b3172d2c2 to your computer and use it in GitHub Desktop.
Note saver in python.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
filename = input("Please enter the filename: ") | |
# Here we check if the file exists | |
if os.path.isfile("./" + filename): | |
print("Looking for file {}...".format(filename)) | |
print("Found it!") | |
action = input( | |
"What would you like to do with the file?\nPossible actions are: read, delete, append, replace\n") | |
if action == "read": | |
print("The content of the file:") | |
with open(filename, "r") as read_file: | |
print(read_file.read()) | |
elif action == "append": | |
text = input("Please enter your note: ") | |
with open(filename, "a") as append_file: | |
append_file.write(text + "\n") | |
elif action == "delete": | |
os.remove("./" + filename) | |
print("{} have been deleted.".format(filename)) | |
# I don't think it makes sense to create a new empty file right after deletion... | |
# Anyway, this is the requested task so here it is | |
with open(filename, "w") as write_file: | |
write_file.write("") | |
elif action == "replace": | |
line_num = int( | |
input("Please enter the line number for the replacement: ")) | |
text = input("Please enter your note: ") | |
with open(filename, "r") as read_file: | |
lines = read_file.readlines() | |
with open(filename, "w") as write_file: | |
for idx, line in enumerate(lines): | |
# print(idx, line) | |
if idx == line_num - 1: | |
print("Line num {} needs to be replaced!".format(line_num)) | |
write_file.write(text + "\n") | |
else: | |
print("Writing \"{}\"".format(line)) | |
write_file.write(line) | |
else: | |
print("Sorry, unrecognized action 😢") | |
else: | |
print("Nope, this file does not exist, I'm going to create it for you! 😄") | |
text = input("Please enter your note: ") | |
with open(filename, "w") as write_file: | |
write_file.write(text + "\n") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment