# Module for operating system calls import os # Module for working with regular expressions import re ''' Example usage of ways to interact with files ''' new_text = "" # Clears terminal based on OS def clear(): if os.name == 'nt': os.system('cls') else: os.system('clear') # open file as read def f_open_read(x): file_name = (x) r = open( file_name , 'r' ) if r.mode == 'r': contents = r.read() r.close() print("%s" % str(contents)) # open file to write to def f_open_write(x, content): file_name = (x) text = (content) f = open( file_name , 'w+' ) f.write(str(text)) f.close() # open file to append to (with a new line char) def f_open_append(x, content): file_name = (x) text = ("\n" + str(content)) f = open( file_name , 'a' ) f.write(str(text)) f.close() ''' # example usage cases: new_text = input("What text do you want to add? \n") f_open_write('text.txt', str(new_text)) f_open_append('text.txt', str(new_text)) f_open_read('text.txt') ''' # using "with" automatically closes file after working with it and is preferable: with open("text.txt", "r") as log: data = log.read() print(data) # Can read and act on individual lines of a doc: with open("text.txt", "r") as log: data = log.readlines() for line in data: print(line) # line.split can be used as field separator: with open("text.txt", "r") as log: data = log.readlines() for line in data: fields = line.split("|") print(fields)