1 import os 2 3 4 class FileUtility(object): 5 # create log folder 6 def create_logs_folder(self, folder_name): 7 project_root = os.path.dirname(os.path.realpath(__file__)) 8 path_separator = os.path.sep 9 file_path = project_root + path_separator + folder_name 10 try: 11 os.makedirs(file_path) 12 except OSError: 13 if not os.path.isdir(file_path): 14 raise 15 16 # write content to a file 17 def write_content_to_file(self, folder_name, file_name, file_type, content_text): 18 project_root = os.path.dirname(os.path.realpath(__file__)) 19 path_separator = os.path.sep 20 file_path = project_root + path_separator + folder_name 21 full_file_name = file_path + path_separator + file_name + file_type 22 try: 23 output_file = open(full_file_name, 'w') 24 output_file.write(content_text) 25 output_file.close() 26 except IOError: 27 print "Cannot write to the file", full_file_name 28 29 # read content from a file 30 def read_file_content(self, folder_name, file_name): 31 project_root = os.path.dirname(os.path.realpath(__file__)) 32 path_separator = os.path.sep 33 file_path = project_root + path_separator + folder_name 34 35 full_file_name = file_path + path_separator + file_name 36 try: 37 file_to_read = open(full_file_name, mode='r') 38 file_content = file_to_read.read() 39 print file_content 40 file_to_read.close() 41 except IOError: 42 print "Could not read file:", full_file_name 43 file_content = "Check the file !!!" 44 print file_content 45 return file_content 46 47 48 if __name__ == "__main__": 49 f = FileUtility() 50 #f.create_logs_folder('log3') 51 #text_content = "this is a test\n" 52 #text_content += "this is a new line test\n" 53 #text_content += "this is another new line test" 54 #f.write_content_to_file('testfiles', 'new_file', '.txt', text_content) 55 f.read_file_content('testfiles', 'new_file.txt') 56