Basic                                                    
***   Programming_Python  
  Ver   Basic  
  7/16/24                                                    
   
  Index 10   Strings https://www.tutorialspoint.com/python/python_strings.htm                            
  Basic
  dotnetperls String Formatting Operator One of Python's coolest features is the string format operator %.
  other This operator is unique to strings and makes up for the lack of having functions from C's printf() family.
  pip #!/usr/bin/python3  
  PySerial print ("My name is %s and weight is %d kg!"   %   ('Zara', 21))          >>>>   My name is Zara and weight is 21 kg!
   
    Format
    S.No. Symbol Conversion   S.No. Symbol Functionality
    1 %c character 1 * argument specifies width or precision
    2 %s string conversion via str() prior to formatting 2 - left justification
    3 %i signed decimal integer 3 + display the sign
    4 %d signed decimal integer 4 <sp> leave a blank space before a positive number
    5 %u unsigned decimal integer 5 # add the octal leading zero ( '0' ) or hexadecimal leading '0x' or '0X', depending on whether 'x' or 'X' were used.
    6 %o octal integer 6 0 pad from left with zeros (instead of spaces)
    7 %x hexadecimal integer (lowercase letters) 7 % '%%' leaves you with a single literal '%'
    8 %X hexadecimal integer (UPPERcase letters) 8 (var) mapping variable (dictionary arguments)
    9 %e exponential notation (with lowercase 'e') 9 m.n. m is the minimum total width and n is the number of digits to display after the decimal point (if appl.)
    10 %E exponential notation (with UPPERcase 'E')
    11 %f floating point real number
    12 %g the shorter of %f and %e
    13 %G the shorter of %f and %E Strings
   
    14   Date and Time https://www.tutorialspoint.com/python/python_date_time.htm                          
   
    Tick Time intervals are floating-point numbers in units of seconds
    Particular instants in time are expressed in seconds since 12:00am, January 1, 1970(epoch).
    There is a popular time module available in Python which provides functions for working with times, and for converting between representations.
    The function time.time() returns the current system time in ticks since 12:00am, January 1, 1970(epoch).
   
    Example Output
    #!/usr/bin/python
    import time;     # This is required to include time module.
    ticks = time.time()
    print "Number of ticks since 12:00am, January 1, 1970:", ticks Number of ticks since 12:00am, January 1, 1970:    7186862.73399
   
    TimeTuple >>>>>>>  This tuple is equivalent to struct_time structure.  This structure has the following attributes --
    Index Field Values         Index Attribute Values      
    0 4-digit year 2008   0 tm_year 2008  
    1 Month 1 to 12   1 tm_mon 1 to 12  
    2 Day 1 to 31   2 tm_mday 1 to 31  
    3 Hour 0 to 23   3 tm_hour 0 to 23  
    4 Minute 0 to 59   4 tm_min 0 to 59  
    5 Second 0 to 61  (60 or 61 are leap-seconds)   5 tm_sec 0 to 61  (60 or 61 are leap-seconds)
    6 Day of Week 0 to 6  (0 is Monday)   6 tm_wday 0 to 6  (0 is Monday)  
    7 Day of year 1 to 366  (Julian day)   7 tm_yday 1 to 366  (Julian day)  
    8 DST -1, 0, 1, -1 means library determines DST   8 tm_isdst -1, 0, 1, -1 means library determines DST
   
    Getting current time To translate a time instant from a seconds since the epoch floating-point value into a time-tuple,
    pass the floating-point value to a function (e.g., localtime) that returns a time-tuple with all nine items valid.
   
    Example Output
    #!/usr/bin/python
    import time;
    localtime = time.localtime(time.time())
    print "Local current time :", localtime Local current time : time.struct_time(tm_year=2013, tm_mon=7, tm_mday=17, tm_hour=21, tm_min=26, tm_sec=3, tm_wday=2, tm_yday=198, tm_isdst=0)
   
   
    Getting formatted time You can format any time as per your requirement, but simple method to get time in readable format is asctime() -
   
    Example Output
    #!/usr/bin/python
    import time;
    localtime = time.asctime( time.localtime(time.time()) )
    print "Local current time :", localtime Local current time :   Tue Jan 13 10:17:09 2009
   
    Example
    import time
    year, month, day, hour, minute = time.strftime("%Y,%m,%d,%H,%M").split(',')
   
    see also datetime Module Example 8.1.4   datetime Objects
    pytz Module import datetime
    dateutil Module now = datetime.datetime.now()
    print now.year, now.month, now.day, now.hour, now.minute, now.second # 2015  5  6  8  53  40
    You don't need separate variables, the attributes on the returned datetime object have all you need.
   
   
      Date and Time
   
    17   Files I/O https://www.tutorialspoint.com/python/python_files_io.htm                            
    Reading Keyboard Input Two built-in functions to read a line of text from standard input, which by default comes from the keyboard.
    The raw_input Function The raw_input([prompt]) function reads one line from standard input and returns it as a string (removing the trailing newline).
    str = raw_input("Enter your input: ");
   
    The input Function The input([prompt]) function is equivalent to raw_input, except that it assumes the input is a valid Python expression and returns the evaluated result to you.
    str = input("Enter your input: ");
   
   
    Opening and Closing Files How to use actual data files.
    Python provides basic functions and methods necessary to manipulate files by default.
    This function creates a file object (fo), which would be utilized to call other support methods associated with it.
   
    The open Function Before you can read or write a file, you have to open it using Python's built-in open() function.
    This function creates a file object (fo), which would be utilized to call other support methods associated with it.
   
    file object = open(file_name [, access_mode][, buffering])
   
    access_modes         File Pointer                
      r Read only (default mode).  Placed at the beginning of the file.  
      rb Read only in binary format (default mode).  Placed at the beginning of the file.  
      r+ Read and Write. Placed at the beginning of the file.  
      rb+ Read and Write in binary format. Placed at the beginning of the file.  
      w Write only.  Overwrites file if exists, else creates a new file.  
      wb Write only in binary format.  Overwrites file if exists, else creates a new file.  
      w+ Write and Read.  Overwrites file if exists, else creates a new file.  
      wb+ Write and Read in binary format.  Overwrites file if exists, else creates a new file.  
      a  Append Placed at the end of file, if exists. If the file does not exist, it creates a new file for writing.
      ab Append in binary format. Placed at the end of file, if exists. If the file does not exist, it creates a new file for writing.
      a+ Append and Read. Placed at the end of file, if exists. If the file does not exist, it creates a new file for writing.
      ab+ Append and Read in binary format.   Placed at the end of file, if exists. If the file does not exist, it creates a new file for writing.
   
   
    file object attributes Once a file is opened and you have one file object, you can get various information related to that file.
   
    Attribute   Description          
    file.closed Returns true if file is closed, false otherwise.  
    file.mode Returns access mode with which file was opened.  
    file.name Returns name of the file.  
    file.softspace Returns false if space explicitly required with print, true otherwise.
    Example
    #!/usr/bin/python
    # Open a file
    fo = open("foo.txt", "wb")
    print "Name of the file: ", fo.name
    print "Closed or not : ", fo.closed
    print "Opening mode : ", fo.mode
    print "Softspace flag : ", fo.softspace
   
   
    file object methods
   
    Method Syntax     
   
    close() fileObject.close(); The close() method of a file object flushes any unwritten information and closes the file object, after which no more writing can be done.
    Python automatically closes a file when the reference object of a file is reassigned to another file. 
    It is a good practice to use the close() method to close a file.
   
    Example
    fo.close()
   
      write() fileObject.write(string); The write() method writes any string to an open file. It is important to note that Python strings can have binary data and not just text.
      The write() method does not add a newline character ('\n') to the end of the string -
     
      Example
    Access #!/usr/bin/python
       Methods # Open a file
      fo = open("foo.txt", "wb") Output of example  
      fo.write( "Python is a great language.\nYeah its great!!\n"); Python is a great language.
      fo.close() Yeah its great!!  
     
     
      read() fileObject.read([count]); The read() method reads a string from an open file. It is important to note that Python strings can have binary data. apart from text data.
    Here, passed parameter is the number of bytes to be read from the opened file. 
    This method starts reading from the beginning of the file and if count is missing,
     then it tries to read as much as possible, maybe until the end of file.
   
    Example
    #!/usr/bin/python
    # Open a file
    fo = open("foo.txt", "r+")
    str = fo.read(10); Output of example  
    print "Read String is : ", str Read String is :  Python is
    fo.close()
   
   
      tell() The tell() method tells you the current position within the file;
    File  in other words, the next read or write will occur at that many bytes from the beginning of the file.
       Positions
      seek(offset[, from]) Changes the current file position. The offset argument indicates the number of bytes to be moved.
    The from argument specifies the reference position from where the bytes are to be moved.
    from reference position
    0 beginning of the file Examples
    1 current position position = fo.tell();
    2 EOF   position = fo.seek(0, 0);
   
   
    Renaming and Deleting Files
   
    The os module Python os module provides methods that help you perform file-processing operations, such as renaming and deleting files.
    (import os) The os module has several methods that help you create, remove, and change directories.
    To use this module you need to import it first and then you can call any related functions.
   
    Method Syntax     
    rename() os.rename(current_file_name, new_file_name) os.rename( "test1.txt", "test2.txt" )
    remove() os.remove(file_name) os.remove("text2.txt")
    mkdir() os.mkdir("newdir") os.mkdir("newdir")
    chdir() os.chdir("newdir") os.chdir("/home/newdir")
    getcwd() os.getcwd() os.getcwd()
    rmdir() os.rmdir('dirname') os.rmdir( "/tmp/test"  )
   
    Summary File Object Methods The file object provides functions to manipulate files. file methods
    OS Object Methods This provides methods to process files as well as directories. os file and directory methods
   
   
    File Methods
    File Methods Table SN Method     Description          
    1 file.close() Close the file. A closed file cannot be read or written any more.
    2 file.flush() Flush the internal buffer, like stdio's fflush. This may be a no-op on some file-like objects.
3 file.fileno() Returns the integer file descriptor that is used by the underlying implementation to request I/O operations from the operating system.
4 file.isatty() Returns True if the file is connected to a tty(-like) device, else False.
????? 5 file.next() Returns the next line from the file each time it is being called.
6 file.read([size]) Reads at most size bytes from the file (less if the read hits EOF before obtaining size bytes).
***** 7 file.readline([size]) Reads one entire line from the file. A trailing newline character is kept in the string.
8 file.readlines([sizehint]) Reads until EOF using readline() and return a list containing the lines. If the optional sizehint argument is present, instead of reading up to EOF, whole lines totalling approximately sizehint bytes (possibly after rounding up to an internal buffer size) are read.
9 file.seek(offset[, whence]) Sets the file's current position
whence
0 default,  absolute file positioning
1 seek relative to the current position
2 seek relative to the file's end
10 file.tell() Returns the file's current position
11 file.truncate([size]) Truncates the file's size. If the optional size argument is present, the file is truncated to (at most) that size.
12 file.write(str) Writes a string to the file. There is no return value.
***** 13 file.writelines(sequence) Writes a sequence of strings to the file. The sequence can be any iterable object producing strings, typically a list of strings.
#!/usr/bin/python'
# Open a file in witre mode
fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name
# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line
seq = ["This is 6th line\n", "This is 7th line"]
# Write sequence of lines at the end of the file.
fo.seek(0, 2)
line = fo.writelines( seq )
# Now read complete file from beginning.
fo.seek(0,0)
for index in range(7):
   line = fo.next()
   print "Line No %d - %s" % (index, line)
# Close opend file
fo.close()
Files I/O