Files

Reading a file

Reading the full content

  • Without exception handling
filename=r"C:\temp\test.txt" #note the r before the text to allow anti-slashes f = open(filename,"r") #"r" means open for reading #load all the file content into a string variable data = f.read() #be careful if the file is big f.close() 
  • With exception-handling
#note the r before the text to allow anti-slashes filename=r"C:\temp\test.txt" try: f = open(filename,"r") #"r" means open for reading #the file could be loaded try: #load all the file content into a string variable data = f.read() #be careful if the file is big except IOError,e: #executed if file was open but could not be read print "Could not read file %s because : %s" % (filename,e) finally: #make sure the file is closed whatever happens f.close() except IOError,e: #this will be executed if an error occurred while opening file print "Could not load file %s because : %s" % (filename,e) 

Reading line-by-line

  • With exception-handling
#note the r before the text to allow anti-slashes filename=r"C:\temp\test.txt" try: f = open(filename,"r") #"r" means open for reading #the file could be loaded try: #loop through lines for line in f.readlines(): #do something with the line (includes new line character at the end) print line except IOError,e: #executed if file was open but could not be read print "Could not read file %s because : %s" % (filename,e) finally: #make sure the file is closed whatever happens f.close() except IOError,e: #this will be executed if an error occurred while opening file print "Could not load file %s because : %s" % (filename,e) 

Writing a file

Overwriting existing file

  • this will create the file if it does not exist
#note the r before the text to allow anti-slashes filename=r"C:\temp\myoutput.out" try: #open for writing : #-will overwrite the file if it exists #-will create the file if it does not exist f = open(filename,"w") #"w" means open for writing #the file could be opened try: f.write("This is a test") f.write("this goes on the same line as previous") f.write("\n")#force a change of line (new-line character) f.write("This is on another line") except IOError,e: #executed if something wrong appens while writing print "Could not read file %s because : %s" % (filename,e) finally: #make sure the file is closed whatever happens f.close() except IOError,e: #this will be executed if an error occurred while opening file print "Could not open file %s for writing because : %s" % (filename,e) 

 

Appending to a file

  • Append data to the end of a file. Useful for logs
#note the r before the text to allow anti-slashes filename=r"C:\temp\myoutput.log" try: #open for appending : #-will append to the end of the file if it exists #-will create the file if it does not exist f = open(filename,"a") #"a" means open for appending #the file could be opened try: f.write("This is a test") f.write("this goes on the same line as previous") f.write("\n")#force a change of line (new-line character) f.write("This is on another line\n") except IOError,e: #executed if something wrong appens while writing print "Could not read file %s because : %s" % (filename,e) finally: #make sure the file is closed whatever happens f.close() except IOError,e: #this will be executed if an error occurred while opening file print "Could not open file %s for appending because : %s" % (filename,e) 

See also

OS

Executing a command

import subprocess proc = subprocess.Popen("ping.exe localhost", stdout=subprocess.PIPE, ) output = proc.communicate()[0] #now output contains the output of the command 

Date/Time

Formatting the current date/time

from datetime import datetime now = datetime.now() #default formats (can change depending on the computer configuration) print now.strftime("%c") #'10/26/09 13:54:32' - the default datetime format on the machine print now.strftime("%x") #'10/26/09' - the default date format on the machine print now.strftime("%X") #'13:54:32' - the default time format on the machine #custom formats print now.strftime("%Y/%m/%d %H:%M:%S") #'2009/10/26 13:54:32' - be careful with upper vs lower-case print now.strftime("%A %d of %B") #'Monday 26 of October' - full names print now.strftime("%a %d %b") #'Mon 26 Oct' - abbreviated names 

Excel

Reading an excel file

  • Use the module xlrd
import xlrd filename = "fichero.xls" book = xlrd.open_workbook(filename) sheet = book.sheet_by_index(0) for row_index in range(sheet.nrows): row = sheet.row(row_index) print row[0] 

 

ODBC

Connecting to a MySQL Database and executing a query

# Importing the ODBC module  import pyodbc # Query to execute: check the number of active sessiones of the Database server queryResponsesTime = "show full processlist" DSNName='MySQL_ODBC_Name' DSNUser='tango04' DSNPassword='*******' # Connection parameters, query building connectionStringiSeries = "DSN=%(DSNName)s;Uid=%(DSNUser)s;Pwd=%(DSNPassword)s;" % \ {'DSNName':DSNName,'DSNUser':DSNUser,'DSNPassword':DSNPassword} try: # Creating the ODBC connection connectionObjResponsesTime = pyodbc.connect(connectionStringiSeries,autocommit=True) try: # Creating a cursor (pointer) to the database cursorResponsesTime= connectionObjResponsesTime.cursor() # Executing the query cursorResponsesTime.execute(queryResponsesTime) # Processing the result Fila=0 SesionesActiv=0 for row in cursorResponsesTime.fetchall() Fila +=1 if row[4] <> 'Sleep': print "Row [%s], State[%s]" % (Fila, row[4]) SesionesActiv +=1 print "Number of processed rows: %d" % cursorResponsesTime.rowcount print "Number of active sessions: %d" % SesionesActiv finally: # Closing the cursor cursorResponsesTime.close() finally: # Closing the connection connectionObjResponsesTime.close() 

 

Persistence

Saving/restoring Python objects

import cPickle f_name = "test.sav" my_object = {} my_object["toto"] = "test" my_object["titi"] = 42 print "storing in %s : %r" % (f_name,my_object) #writing an object to a file f = open(f_name,"w") P = cPickle.Pickler(f) P.dump(my_object) f.close() #loading an object from a file f = open(f_name,"r") U = cPickle.Unpickler(f) d = U.load() f.close() print "Loaded from %s : %r" % (f_name,d) 

 

Reload a module

If you want to put some part of the python in an external script, and don't want to restart the ThinkServer to get the last version

if VSMScriptFirstEvent: import toto reload(toto) 

 

See also


Still have questions? We can help. Submit a case to Technical Support.

Last Modified On: October 22, 2018