Hi,
When i am running this code i am getting a Unicode error half way through. Not sure what mxd/layer file name is hanging it up (line 33) on but not sure where to put the fix (line 7 - or if this is the correct fix) either.
import arcpy, os #code adds mxd name and layer path name to text file separated by a comma arcpy.env.overwriteOutput = True #def Utf8EncodeArray(oldArray): #newArray = [] #for element in oldArray: #if isinstance(element, unicode): #newArray.append(element.encode("utf-8")) #else: #newArray.append(element) #return newArray path = "////serverpath" #path2 = mxdlst = [] txt = open("text file path", 'w') print "making mxd list" for root, dirs, files in os.walk(path): for fname in files: if fname.endswith(".mxd"): mxd = root + '\\' + fname mxdlst.append(mxd) del mxd, fname for mapdoc in mxdlst: mxd = arcpy.mapping.MapDocument(mapdoc) for df in arcpy.mapping.ListDataFrames(mxd, "*"): for lyrlst in arcpy.mapping.ListLayers(mxd, "*", df): if lyrlst.supports("DATASOURCE"): txt.write(mapdoc + "," + lyrlst.workspacePath + "\\" + lyrlst.name + "\n") print "adding" + mapdoc + "," + lyrlst.workspacePath + "\\" + lyrlst.name + "\n" else: txt.write(mapdoc + "," + lyrlst.name + "\n") print "adding" + mapdoc + "," + lyrlst.name + "\n" txt.close() del mxd, df, lyrlst, mapdoc, mxdlst
is this how to do it?
txt.write(u'mapdoc' + "," + u'lyrlst.workspacePath' + "\\" + u'lyrlst.name' + "\n")
This will not be the solution due to a number of reasons:
If you use something like u'lyrlst.workspacePath', then you create a unicode text contains the text lyrlst.workspacePath and not the content of the variable. For that you would have to use unicode(lyrlst.workspacePath).
The other aspect is combining a normal str with a unicode. In your line there are still some elements that are of type str ("," "\\", "\n", etc).
I have seen posts where they recommend using the codecs library to write unicode to text file:
import codecs with codecs.open(YourOutputFile, 'w', encoding='utf-8') as f: f.write(unicode_text)
Please take the time to read this article: Solving Unicode Problems in Python 2.7 | Azavea Labs It can help to clear thing up for you.