Skip to content

Instantly share code, notes, and snippets.

@c0derabbit c0derabbit/myio.py

Last active Sep 9, 2016
Embed
What would you like to do?
Python module for basic I/O operations
def read(filename):
'''
Opens a file and prints its lines in the console.
Takes 1 arg (string): filename
'''
with open(filename) as f:
for line in f:
print(line.rstrip())
def add(filename, text):
'''
Opens a file and adds the text to the end.
Takes 2 args (strings): filename, text to add
'''
with open(filename, 'a') as f:
f.write(text)
def write(filename, text):
'''
Opens a file and writes the string in it.
CAUTION: Overwrites content!
Takes 2 args (strings): filename, text to write
'''
with open(filename, 'w') as f:
f.write(text + '\n')
def chars(filename):
'''
Counts characters in file.
Takes 1 arg (string): filename
'''
count = 0
with open(filename) as f:
for line in f:
count += len(line)
print(count)
if __name__ == '__main__':
def do():
f = input('Enter file name: ')
mode = input('Choose mode (r = read, a = add text, w = write, c = character count): ')
if mode == 'r':
read(f)
elif mode == 'a':
text = input('Enter text: ') + '\n'
add(f, text)
elif mode == 'w':
text = input('Enter text: ') + '\n'
write(f, text)
elif mode == 'c':
chars(f)
else:
print('Mode not recognised, please enter \'r\', \'a\', \'w\' or \'c\'.')
do()
do()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.