Skip to content

Instantly share code, notes, and snippets.

@eszterkv
Last active September 9, 2016 11:34
Show Gist options
  • Save eszterkv/dc89e1293e635cdb03c3de08aebdaeee to your computer and use it in GitHub Desktop.
Save eszterkv/dc89e1293e635cdb03c3de08aebdaeee to your computer and use it in GitHub Desktop.
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