Skip to content

Instantly share code, notes, and snippets.

@shinysu
Last active November 3, 2020 08:52
Show Gist options
  • Save shinysu/12bff463c62a5c940e56311ee69cff84 to your computer and use it in GitHub Desktop.
Save shinysu/12bff463c62a5c940e56311ee69cff84 to your computer and use it in GitHub Desktop.
Programs using files
'''
program to read from a file using read() and write to another file using write()
'''
with open("input.txt","r") as reader:
lines = reader.read()
with open("output.txt","w") as writer:
writer.write(lines)
'''
Using readlines() to read the contents of the file. It reads the contents of the file and returns a list of lines.
strip('\n') is used to strip the newline character from the end of the string
'''
with open("input.txt") as reader:
lines = reader.readlines()
for x in lines:
print(x.strip('\n'))
'''
The todolist version using a list variable
'''
def add_item():
item = input("Enter the new item:")
todolist.append(item)
def remove_item():
item = input("Enter the item to be removed: ")
todolist.remove(item)
todolist = []
while True:
print("Press\n 1 to add item \n 2 to remove item \n 3 to exit")
choice = int(input())
if choice == 1:
add_item()
elif choice == 2:
remove_item()
else:
break
print(todolist)
'''
Todolist using files for storage
'''
def read_file():
tasks = []
with open("task.txt", "r") as reader:
lines = reader.readlines()
for line in lines:
tasks.append(line.strip('\n'))
return tasks
def write_file(tasks):
with open("task.txt", "w") as writer:
for line in tasks:
writer.write(line + "\n")
def add_item():
item = input("Enter the new item:")
todolist.append(item)
def remove_item():
item = input("Enter the item to be removed: ")
todolist.remove(item)
todolist = read_file()
print(todolist)
while True:
print("Press\n 1 to add item \n 2 to remove item \n 3 to exit")
choice = int(input())
if choice == 1:
add_item()
elif choice == 2:
remove_item()
else:
break
print(todolist)
write_file(todolist)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment