how to do lowercase of 'xl cell value + some content/somethng '? - python-2.7

here my function . I have to do lower what ever coming in newfilename..i.e newfilename.lower()
def my_function(start, end):
sheetname = 'my-sheet'
filepath = "/myxl.xlsx"
try:
work_book=xlrd.open_workbook(filepath)
except:
print 'error'
try:
worksheet = work_book.sheet_by_name(sheetname)
except:
print 'error'
rows=worksheet.nrows
cols=worksheet.ncols
success = []
fail = []
for row in xrange(start,end):
print "row no. : ",row
state = '/home/myfolder/'
if os.path.exists(state):
print "state folder exits"
else:
os.makedirs(state)
district = state + worksheet.cell_value(row,0) + '/'
if os.path.exists(district):
print "district folder exits"
else:
os.makedirs(district)
city = district + worksheet.cell_value(row,2) + '/'
if os.path.exists(city):
print "city folder exits"
else:
os.makedirs(city)
newfilename = city + worksheet.cell_value(row,4).replace (" ", "-") + '.png'
if worksheet.cell_value(row,5) !="":
oldfilename = worksheet.cell_value(row,5)
else:
oldfilename="no-image"
newfullpath = newfilename
oldfullpath = '/home/old/folder/' + oldfilename
try:
os.rename(oldfullpath,newfullpath)
success.append(row)
except Exception as e:
fail.append(row)
print "Error",e
print 'renaming done for row #' ,row , ' file ', oldfilename , ' to ', newfilename
print 'SUCCESS ', success
print 'FAIL ', fail
newfilename.lower() not working
here when I am going to use unicode error coming...
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 72: ordinal not in range(128)

Related

string concat causing 'str' object has no attribute 'object'

I have a view like below:
I get the error: 'str' object has no attribute 'object'
it must have something to do with my string concat - what has gone wrong :)
thanks
def edit_skill_plan(request):
#t = skills.objects.get(skill_id='django_5158517')
skillid = request.POST.get('editbut')
user = request.user
t = skills.objects.get(creator=user, skill_id=skillid)
t.status = 'closed'
t.save() # this will update only
complete_date = datetime.today().strftime('%Y-%m-%d')
week_num = datetime.today().strftime('%V')
x = t.skill_name
user = request.user
points = t.points
cat = t.category
year = datetime.today().strftime('%Y')
status = str(request.user.username) +' completed the task: ' + str(x) + ' which was worth: ' + str(points) + ' points'
status.object.create(creator=user, status=status, status_date=complete_date)
Your last two line should be,
status_code = str(request.user.username) +' completed the task: ' + str(x) + ' which was worth: ' + str(points) + ' points'
status.object.create(creator=user, status=status_code, status_date=complete_date)

IndexError: string index out of range in python2.7

Could someone help me out with what is going wrong and what I can do to fix it?
File "C:/Users/rawaa/raw/untitled2.py", line 246, in disp_message
str02= str02 + str01[single]
IndexError: string index out of range
def disp_message(val01, file_name):
f = open(file_name,'r')
data = f.readlines()
f.close()
str01 = str(data[0])
str02 = ' '
for each in val01:
#print each
for single in each:
#print single
str02= str02 + str01[single]
str02 = str02 + ' '
print("the hidden message in the data is:")
print(str02)
print("\n\npress 1. to see hidden data visualisation or ctrl+c to terminate")
cho = raw_input()
if cho == '1':
print(show_data(str01,1,val01))
you didn't specify the range of length of each, you should do maybe :
for each in val01:
#print each
for single in range (len(each)):
#print single
str02= str02 + str01[single]
str02 = str02 + ' '

trying to compare file with a dictionary python 2.7 No output

basically i'm trying to read the file below and comparing the fruit that the person wants with the fruit in the dictionary and if the stock is above 0 then print a message saying they have been given the fruit and if stock is 0 then a message saying not fruit was given etc.
the error im getting is: "IndexError: list index out of range" on the first line of my if statement
[
["James Bruce", "Bananas"],
["Katherine Newton", "Bananas"],
["Deborah Garcia", "Pears"],
["Marguerite Kozlowski", "Pineapples"],
["Kenneth Fitzgerald", "Pineapples"],
["Ronald Crawford", "Bananas"],
["Donald Haar", "Apples"],
["Al Whittenberg", "Bananas"],
["Max Bergevin", "Bananas"],
["Carlos Doby", "Pears"],
["Barry Hayes", "Pineapples"],
["Donald Haar", "Bananas"]
]
the dictionary: {"Apples": 14, "Bananas": 14, "Pineapples": 0, "Pears": 8}
import json
import json
json_Queue = open ("C:\Users\dylan gornall\Desktop\Dylan's Uni
Work\queue.json").read ()
json.loads(json_Queue)
from ast import literal_eval
with open("C:\Users\dylan gornall\Desktop\Dylan's Uni Work\stock.json") as f:
a = f.read()
dic = literal_eval(a)
s = open ("C:\Users\dylan gornall\Desktop\Dylan's Uni Work\queue.json", 'r')
for line in s:
parts = line.split(',')
if len(parts) >1 and parts[1] == "Pears" and dic["Pears"]:
print( parts[0] + ' has been given ' + parts[1] )
elif len(parts) >1 and parts[1] == "Apples" and dic["Apples"] >= 1 :
print( parts[0] + ' has been given ' + parts[1] )
elif len(parts) >1 and parts[1] == "Bananas" and dic["Bananas"] >= 1 :
print( parts[0] + ' has been given ' + parts[1] )
elif len(parts) >1 and parts[1] == "Pineapples" and dic["Pineapples"] >= 1 :
print( parts[0] + ' has been given ' + parts[1] )
elif len(parts) >1 and parts[1] == "Pineapples" and dic["Pineapples"] == 0 :
print(parts[0] + " was not given " + parts[1])
elif len(parts) >1 and parts[1] == "Apples" and dic["Apples"] == 0 :
print(parts[0] + " was not given " + parts[1])
elif len(parts) >1 and parts[1] == "Pears" and dic["Pears"] == 0 :
print(parts[0] + " was not given " + parts[1])
elif len(parts) >1 and parts[1] == "Bananas" and dic["Bananas"] == 0 :
print(parts[0] + " was not given " + parts[1])
If you do print line in your loop for, the first one is just a [ so doing parts = line.split(',') give you only one element in parts, and parts[1] does not exist. You get the error you mentioned even if you check for len(parts) >1 as python does not stop at this check and do the parts[1], being then out of range.
Now, for your code, I think you can make it a bit shorter, if the queue.json is exactly how you showed it.
import json
json_Queue = open ("C:\Users\dylan gornall\Desktop\Dylan's Uni Work\queue.json").read()
# here I define the dict but you can do as you did, just I don't have the file
dic = {"Apples": 14, "Bananas": 14, "Pineapples": 0, "Pears": 8}
# Define s using json.loads, then s is a list of list
s = json.loads(json_Queue)
for person_fruit in s:
#here the first person_fruit = [u'James Bruce', u'Bananas'], already a list
person = person_fruit[0]
fruit = person_fruit[1]
if fruit in dic.keys():
if dic[fruit] >=1:
print (person + ' has been given ' + fruit)
# here I don't know if you want to change the number of fruit in your dic but if you do, you need:
# dic[fruit] = dic[fruit] - 1
else:
print (person + " was not given " + fruit)
else:
print (person + " was not given " + fruit + " as we never had this fruit in our stock")
Hope it helps you

Text wrap formatting error fixing

I am working in the textwrap module that requires the outputted text to look like see picture of expected output formatting
However, my output looks like:
see my output
This is the code I am using for the text wrap:
wrap = textwrap.TextWrapper(initial_indent = ' '*4, subsequent_indent = ' '*4)
if name not in bus_name:
print 'This business is not found'
else:
count = 0
for id in bus_name[name]:
if id not in bus_review:
print 'No reviews for this business are found'
else:
for rev in bus_review[id]:
print 'Review %d' %(count+1)
string = textwrap.fill(rev)
string = string.replace(' ', '$')
string = wrap.fill(string)
string = string.replace('$', '\n'+' '*4)
print '%s' %string
print
count += 1

Find and later delete zombie informatica objects

Is there a easy way to identify and clean unused informatica artifacts?
Context: In one of the projects, there are lot of zombie sessions / mappings etc, the creators have long gone.
I want to do the following:
List/Delete all sessions that are not associated with a workflow.
List/Delete all mappings that are not used in any session/wf.
List/Delete all source/target that were not used in any mapping.
List/Delete all workflows that were not run in the past one year.
Someone mentioned about using : Designer > Tools > Queries . I can't express the above 1/2/3/4 with the option given, can anyone shed some light?
Note:
I’m not looking for click one by one and find dependencies.
I’m not looking for download the whole plant as xml and search dependencies
one by one
As this is not easily achievable with PowerCenter itself, I tried to come up with some simple tool to solve it. For the full description and download link please go to this page.
Below you'll find the code published as requested in comments: Find and later delete zombie informatica objects
Feel free to use, share and improve :) Any code review will be also much appreciated.
import subprocess
import os
from subprocess import *
import platform
import sys
import getpass
import configparser
#global variables declarations
currentDir=''
pmrepPath=''
domainFile=''
def connect_to_repo(Repository,Domain,User,Host,Port, UserSecurityDomain):
#password = raw_input("Enter password for Repository: " + Repository + ", User: " + User)
password = getpass.getpass()
print "\nConnecting..."
if Domain != '':
RepoCommand="pmrep connect -r "+Repository+" -d "+Domain+" -n "+User + " -x " + password #+" -X DOMAIN_PWD"
else:
RepoCommand="pmrep connect -r "+Repository+" -n "+User + " -x " + password + " -h " + Host + " -o " + Port
if UserSecurityDomain != '':
RepoCommand += " -s " + UserSecurityDomain
RepoCommand=RepoCommand.rstrip()
p=subprocess.Popen(RepoCommand,stderr=subprocess.PIPE,stdin=subprocess.PIPE,stdout=subprocess.PIPE,shell=True)
out,err=p.communicate()
if p.returncode or err:
print "Connection Failed"
print err.strip()
print out.strip()
sys.stdout.flush()
sys.stdin.flush()
else:
print "Connection Successful"
sys.stdout.flush()
sys.stdin.flush()
return p.returncode
def execute_pmrep_command(command, output_file_name, start_line, end_line, line_prefix):
if len(line_prefix)>0: line_prefix+=' '
out=open(output_file_name,'a')
return_code=subprocess.Popen(command,stdin=subprocess.PIPE,stdout=subprocess.PIPE,shell=True)
output,error=return_code.communicate()
for line in output.split('\r\n')[start_line:end_line]:
out.writelines(line_prefix + line + '\n')
out.close()
return
def check_platform():
global domainFile
global currentDir
global pmrepPath
global platForm
platForm=platform.system()
print "Platform recognized : "+platForm
## if not os.getenv('INFA_HOME', 'C:\\Informatica\\9.5.1'):
## print "INFA_HOME env_variable not set in your "+platForm+" platform."
## print "Please set INFA_HOME and continue."
## raw_input()
## sys.exit(0)
if not os.getenv('INFA_DOMAINS_FILE'):
print "INFA_DOMAINS_FILE env_variable not set in your "+platForm+" platform."
print "Please set INFA_DOMAINS_FILE and continue."
raw_input()
sys.exit(0)
## elif not os.getenv('DOMAIN_PWD', 'vic'):
## print "DOMAIN_PWD env variable not set in your "+platForm+" platform."
## print "Please set DOMAIN_PWD and continue."
## raw_input()
## sys.exit(0)
## else:
## if platForm == 'Windows':
## pmrepPath=os.getenv('INFA_HOME').strip()+"\clients\PowerCenterClient\client\\bin"
## elif platForm == 'Linux':
## pmrepPath=os.getenv('INFA_HOME').strip()+"/server/bin"
## currentDir=os.getcwd()
## domainFile=os.getenv('INFA_DOMAINS_FILE','C:\\Informatica\\9.5.1\\domains.infa').strip()
config = configparser.RawConfigParser()
config.optionxform = lambda option: option
config.read('InfaRepo_ListUnusedObjects.cfg')
infaDir = config.get('Common', 'infaDir').strip()
Repository = config.get('Common', 'Repository').strip()
Domain = config.get('Common', 'Domain').strip()
Host = config.get('Common', 'Host').strip()
Port = config.get('Common', 'Port').strip()
Folder = config.get('Common', 'Folder').strip()
User = config.get('Common', 'User').strip()
UserSecurityDomain = config.get('Common', 'UserSecurityDomain').strip()
objectTypeList = config.get('Common', 'objectTypeList').split(',')
if Domain != '':
print 'Domain provided, will be used to connect.'
else:
print 'Domain not provided, Host and Port will be used to connect.'
for i in range(len(objectTypeList)):
objectTypeList[i]=objectTypeList[i].strip()
currentDir=os.getcwd()
outputDir=currentDir+'\\UnusedObjectsReport'
###objectTypeList = ['mapplet', 'mapping', 'session', 'source', 'target', 'worklet']
##
##objectTypeList = ['target']
pmrepPath=infaDir.strip()+"\clients\PowerCenterClient\client\\bin"
os.chdir(pmrepPath)
outFile = outputDir + "\ListOfUnusedObjects.txt"
if not os.path.exists(os.path.dirname(outFile)):
os.makedirs(os.path.dirname(outFile))
print 'Output file: ' + outFile
open(outFile,'w').writelines("Domain : "+Domain+"\nRepository : "+Repository+"\nUserName : "+User+"\n")
open(outFile,'a').writelines("***************************"+"\n")
open(outFile,'a').writelines("LIST OF UNUSED OBJECTS:\n")
outBatchFile = outputDir + "\DeleteUnusedObjects.bat"
tempDir = outputDir + "\\temp"
if not os.path.exists(outputDir):
os.makedirs(outputDir)
if not os.path.exists(tempDir):
os.makedirs(tempDir)
for tempFile in os.listdir(tempDir):
os.remove(os.path.join(tempDir, tempFile))
print 'Output batch file: ' + outBatchFile
if Domain != '':
RepoCommand="pmrep connect -r "+Repository+" -d "+Domain+" -n "+User
else:
RepoCommand="pmrep connect -r "+Repository+" -n "+User + " -h " + Host + " -o " + Port
if UserSecurityDomain != '':
RepoCommand += " -s " + UserSecurityDomain
open(outBatchFile,'w').writelines(pmrepPath+"\\"+RepoCommand+"\n")
objectTypeCounter=0
return_code=connect_to_repo(Repository,Domain,User,Host,Port,UserSecurityDomain)
objDepDict={}
error = False
errorList = []
#check if repository connection is successfull
if return_code==0:
for objectType in objectTypeList:
objectTypeCounter+=1
print "Step {0} of {1}: {2}".format(objectTypeCounter, len(objectTypeList), objectType)
objectFile = tempDir + "\\" + objectType + ".txt"
open(objectFile,'w').writelines("")
objectDepFile = tempDir + "\\" + objectType + "_dep.txt"
open(objectDepFile,'w').writelines("")
execute_pmrep_command("pmrep listobjects -f " + Folder + " -o " + objectType, objectFile, 8, -4, '')
objectList=open(objectFile).readlines()
objectCounter=0
if len(objectList) == 0:
print '\tNo {0}s found'.format(objectType)
elif objectList[0][:3] == ' [[':
error=True
for line in objectList:
errorList += [line.replace('\n','')]
break
for line in objectList:
objectCounter+=1
fields=line.split(' ')
if len(fields) == 2:
objectType=fields[0]
objectName=fields[1][:-1]
else:
objectType=fields[0]
objectName=fields[2][:-1]
#if the object is non-reusable, it obviously is in some workflow, so skipp it
if fields[1] == 'non-reusable':
print "\t{0} {1} of {2}: {3} is not a reusable {4} - skipping".format(objectType, objectCounter, len(objectList), objectName, objectType)
continue
command = "pmrep listobjectdependencies -f " + Folder + " -n " + objectName + " -o " + objectType + " -p parents"
#print "Getting object dependencies for " + objectType + " " + objectName
print "\t{0} {1} of {2}: {3}".format(objectType, objectCounter, len(objectList), objectName)
execute_pmrep_command(command, objectDepFile, 8, -6, objectName)
#find unused objects
for fileLine in open(objectDepFile,'r').readlines():
line = fileLine.split(' ')
if len(line) == 3:
Name = line[0]
ParentType = line[1]
ParentName = line[2]
else:
Name = line[0]
ParentType = line[1]
ParentName = line[3]
try:
objDepDict[objectType + ': ' + Name]+=[ParentType + ' ' + ParentName]
except:
objDepDict[objectType + ': ' + Name]=[ParentType + ' ' + ParentName]
found = False
for objectKey in objDepDict.iterkeys():
objectType, objName = objectKey.replace(' ','').split(':')
if len(objDepDict[objectKey]) <= 1:
if not found:
print '\n'
print 'Following unused objects have been found:'
found = True
print '\t{0}: {1}'.format(objectType, objName)
open(outFile,'a').writelines('{0}: {1}\n'.format(objectType, objName))
open(outBatchFile,'a').writelines("rem {0}\\pmrep deleteobject -f {1} -o {2} -n {3}\n".format(pmrepPath, Folder, objectType, objName))
execute_pmrep_command('pmrep cleanup', 'log.txt', 0, 0, '')
open(outBatchFile,'a').writelines(pmrepPath+'\\pmrep cleanup' + '\n')
if not error:
if not found:
print 'No unused objects found.'
print '\nDone.'
print 'Output file: ' + outFile
print 'Output batch file: ' + outBatchFile
else:
print 'Following errors occured:'
for e in errorList:
print '\t', e
#wait for key press
print '\nHit Enter to quit...'
raw_input()
#End of program