# io.py ''' A few ways on how to format output and handle files (read/write). ''' # # String output. # # Standard string output. print("Hello World!") # Convert objects into strings. E.g. numbers. my_string = "number = " + str(4) # str uses the __str__ method of the object. a = 5 my_string = "number = " + a.__str__()) # Alternative function: repr(). my_string = "number = " + repr(4) # For fancier output we can use the string method 'format'. print("number = {0}".format(3.2)) print('We are the {} who say "{}!"'.format('knights', 'Ni')) print("a = {0}, b = {1}".format(5, 6)) print("a = {a}, b = {b}".format(a=5, b=6)) # Greater control using the colon :. print('The value of PI is approximately {0:.3f}.'.format(np.pi)) print("number = {0:3.2e}".format(123456.123456789)) name = "Pete" phone = 12345 print('{0:10} ==> {1:10d}'.format(name, phone)) # Find first occurrence of substring. "Python".find('th') # Find and replace all occurrences of substring. "Hello World!".replace('World', 'Python') # Split the string at specified character. '1,2,3'.split(',') # Check starting substring. "Hello".startswith('He') # Swap case. "Hello".swapcase() # # Files: read/write. # # Open file. my_file = open('time_series.dat', 'r') # The second argument specifies the options: # r: read # w: write # a: append # b: binary # Mind the order: 'wr', 'br', 'ar', not 'rw', 'rb', 'ra'. # Read the entire file or a specified length. my_file = open('test_file', 'r') print(my_file.read(10)) print(my_file.read()) # Find current location in file. my_file.tell() # Specify location in file. my_file.seek(5) # Close the file. my_file.close() # Read only one line. my_file.readline() # Read all the lines. print(my_file.readlines()) # Loop over lines in the file. for line in my_file: print(line) # Writing into a file requires to open it with the 'w' or 'a' option. my_file.write("some string")