Python, WindowsError: [Error 32], file being used by another process - python-2.7

I'm writing a small programm that's supposed to loop through a folder of msg files (i.e. MS Outlook emails) and prefix a short string to their file names. I keep running into WindowsError: [Error 32] (The process cannot access the file because it is being used by another process) on line 33 (os.rename(filenameOLD, filenameNEW)). Any idea why?
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
import os
path = 'C:\Users\MyName\Desktop\SomeFile\\'
msgFiles = os.listdir(path) # returns list
count = 0
for msgFile in msgFiles:
count = count + 1
msg = outlook.OpenSharedItem(path + msgFile)
date = str(msg.SentOn)
#Extract YYYY, MM, DD, HHMMSS from .msg sent date
YYYY = str(20)+date.split("/")[2][:2]
MM = date.split("/")[1]
DD = date.split("/")[0]
HHMMSS = "".join(date.split()[1].split(":")) + "Hrs"
#Reformat date to valid file name
filenamePrefix = YYYY + DD + MM + " " + HHMMSS + " "
#generate new file name
filenameOLD = path + msgFile
filenameNEW = path + filenamePrefix + msgFile
#rename file
os.rename(filenameOLD, filenameNEW)
print count, "files renamed"

You've opened the message without closing it. Instead do:
# ...
for msgFile in msgFiles:
count = count + 1
msg = outlook.OpenSharedItem(path + msgFile)
date = str(msg.SentOn)
del msg
# ...

Related

What does TypeError: 'file' object has no attribute '__getitem__' mean?

I have this code:
My_Directory = r"/Users/schuylerraeschroerborges/Desktop/Mars_Project/mcam_image_and_label/0984MR0043380090502893E01_DRCL" # Get data from directory
My_Extension = ".LBL"
WorkingDirectory = "/Users/schuylerraeschroerborges/Desktop/Mars_Project/" # Work in same directory
f = open('mcam_image_and_label/0984MR0043380090502893E01_DRCL.LBL','r') # Open label file
lines = f.readlines() #index lines
g = open('Expanded_data.csv','w+') # Write in excel spreadsheet
lines = g.readlines()
ID_line = f[21]
ID = re.split('"',f[21])[2]
LO_line = f[134]
LO = re.split('(',f[134])[2]
DI_line = f[442]
DI = re.split('=',f[442])[2]
AZ_line = f[445]
AZ = re.split('=',f[445])[2]
VE_line = f[446]
VE = re.split('=',f[446])[2]
newline = ID + '\t' + LO + '\t' + DI + '\t' + AZ + '\t' + VE + '\n'
g.writelines(newline)
I keep gettting this error, TypeError: 'file' object has no attribute '_getitem__', after I run the code in Python 2.7. What does this error mean? Do I need to change the name of a file or something?
You are trying to index object f which is a file like object returned by open() function.
Internally, indexing is implemented via __getitem__ special method which the file object doesn't implement, this is the reason you are seeing that error message.
The error is on the line where you are trying to assign ID_lines = f[21], perhaps you want to assign lines[21] instead.

Getting a datetime object from strptime

I'm trying to write a script that formats the date in a log file. The log file is meant to be read by excel after the conversion.
import datetime
def excel_date(date1):
temp = dt.datetime(1899, 12, 30)
delta = date1 - temp
return float(delta.days) + (float(delta.seconds) / 86400)
data=open(".\input.log").read()
file_ = open('output.log', 'w')
for row in data.split('\n'):
prefix = row[:1]
sdate = row[1:29]
suffix = row[30:]
offset = datetime.timedelta(0)
dt = datetime.datetime.strptime(sdate, '%a %b %d %H:%M:%S.%f %Y') + offset
excelDate = excel_date(dt)
file_.write(dt.strftime('%d.%m.%Y %H:%M:%S') + "\t" + excelDate + "\t"+ suffix + "\n")
file_.close()
The problem occurs when I try to use the excel_date function. I know that strptime returns a string and that the function expects a datetime object. Is there a way of creating a datetime object from strptime or converting the string into one?
Thanks

print if list index out of range

hi all im trying to create a handle for "list index out of range" but seem not to be having any luck.
import json, urllib, re
from urllib import urlencode
import googlemaps
import tempfile
import win32api
import win32print
start = "Adelaide, South Australia"
finish = " ghkjffzh, south Australia "
url = 'http://maps.googleapis.com/maps/api/directions/json?%s' % urlencode((
('origin', start),
('destination', finish)
))
ur = urllib.urlopen(url)
result = json.load(ur)
filename = "output.txt"
with open(filename, 'w') as output:
for i in range(0, len(result['routes'][0]['legs'][0]['steps'])):
try:
s = (result['routes'][0]['legs'][0]['steps'][i]['html_instructions'])
d = (result['routes'][0]['legs'][0]['steps'][i]['distance']['text'])
l = (result['routes'][0]['legs'][0]['steps'][i]['duration']['text'])
s = re.sub('<[A-Za-z\/][^>]*>', '', s)
output.writelines(s + " " + d + " " + l + '\n')
except Exception:
print "Directions could not be printed"
output.write("Directions could not be given due to the format of page or the address type")
but nothing is written to .txt and still get error.
ive tried to replace Exception with IndexError and VauleError but no change
Solved used by exploring the returned json result and found a Status result so I passed that first.
with open(filename, 'w') as output:
if result ['status'] == "NOT_FOUND"
output.write( " no directions avalible")
else:
for i in range(0, len(result['routes'][0]['legs'][0]['steps'])):
s = (result['routes'][0]['legs'][0]['steps'][i]['html_instructions'])
d = (result['routes'][0]['legs'][0]['steps'][i]['distance']['text'])
l = (result['routes'][0]['legs'][0]['steps'][i]['duration']['text'])
s = re.sub('<[A-Za-z\/][^>]*>', '', s)
output.writelines(s + " " + d + " " + l + '\n')

Python struct.error: unpack requires a string argument of length 2

I have written some data using C++ in byte format. I am now trying to read that data again using Python, but I run into an error;
Traceback (most recent call last):
File "binary-reader.py", line 61, in <module>
interaction_types.append(struct.unpack('<H',fp.read(2))[0]);
struct.error: unpack requires a string argument of length 2
I don't really understand since it looks like I am giving a string of length 2, right? Furthermore, I do the same thing at line 32
There is another question like mine but it is without an answer is targeted for Python 3.
Here is my code
import sys
import struct
import os
print "Arguments : "
print str(sys.argv)
#N = #isects
# 2 2 3*4 2 3*4*N 4N 4N 3*4N 2N 2N
#imageX,imageY,throughput,#isects,isect_positions,primitive_ids,shape_ids,spectra,interaction_types,light_ids
file_path = str(sys.argv[1]);
byte_count = 0;
line_number = 1;
fp = open(file_path, "rb");
output = open('output.txt',"w");
file_size = os.path.getsize(file_path)
print "(input) file size = " + str(file_size);
while byte_count < file_size:
print "Line number = " + str(line_number)
print "Current byte count = " + str(byte_count)
# Do stuff with byte.
x = struct.unpack('<H', fp.read(2))[0]
y = struct.unpack('<H', fp.read(2))[0]
throughputOne = struct.unpack('<f', fp.read(4))[0]
throughputTwo = struct.unpack('<f', fp.read(4))[0]
throughputThree = struct.unpack('<f', fp.read(4))[0]
nrIsects = struct.unpack('<H',fp.read(2))[0]
# print "x = " + str(x)
# print "y = " + str(y)
# print "throughputOne = " + str(throughputOne)
# print "throughputTwo = " + str(throughputTwo)
# print "throughputThree = " + str(throughputThree)
print "nrIsects = " + str(nrIsects)
isect_positions = []
for i in range(nrIsects*3):
value = struct.unpack('<f',fp.read(4))[0]
isect_positions.append(value);
primitive_ids = []
for i in range(nrIsects):
value = struct.unpack('<I',fp.read(4))[0]
primitive_ids.append(value);
shape_ids = []
for i in range(nrIsects):
shape_ids.append(struct.unpack('<I',fp.read(4))[0]);
spectra = []
for i in range(nrIsects*3):
spectra.append(struct.unpack('<f',fp.read(4))[0]);
interaction_types = []
for i in range(nrIsects):
interaction_types.append(struct.unpack('<H',fp.read(2))[0]);
light_ids = []
for i in range(nrIsects):
light_ids.append(struct.unpack('<H',fp.read(2))[0]);
output_vars = [x,y,throughputOne,throughputTwo,throughputThree,nrIsects]
line_string = ""
for i in range(len(output_vars)):
output.write(str(output_vars[i]))
line_string += str(output_vars[i])
if i is not len(output_vars) - 1:
output.write(',')
line_string += ','
print line_string
#Update counters
byte_count += 18 + 36*nrIsects
line_number+=1
# raw_input('Press any key to continue.');
# print byte
And here is a link to a input file to use. You can run the code by passing a commandline argument specifying the path of the binary file. I have also written the code in ASCII, which reads
0,0,[0.127076,0.127076,0.127076],1,{[0.144978,-0.294863,2.991749]},{3917},{3916},{[1.375603,1.375603,1.375603]},{5},{0}
https://www.dropbox.com/s/tu1anqo5k0ygtd6/writetest.bin
EDIT: The layout of my file can be found as a comment in the code
50 bytes have already been read before the fp.read(2) that raises the error. Thus, fp.read(2) returns an empty string, and struct.unpack raises an exception:
In [83]: 2+2+4+4+4+2+12+4+4+12
Out[83]: 50
x = struct.unpack('<H', fp.read(2))[0] # 2 bytes read
y = struct.unpack('<H', fp.read(2))[0] # 2 bytes
throughputOne = struct.unpack('<f', fp.read(4))[0] # 4 bytes
throughputTwo = struct.unpack('<f', fp.read(4))[0] # 4 bytes
throughputThree = struct.unpack('<f', fp.read(4))[0] # 4 bytes
nrIsects = struct.unpack('<H',fp.read(2))[0] # 2 bytes
print "nrIsects = " + str(nrIsects)
isect_positions = []
for i in range(nrIsects*3):
value = struct.unpack('<f',fp.read(4))[0] # 12 bytes
isect_positions.append(value)
primitive_ids = []
for i in range(nrIsects):
value = struct.unpack('<I',fp.read(4))[0] # 4 bytes
primitive_ids.append(value)
shape_ids = []
for i in range(nrIsects):
shape_ids.append(struct.unpack('<I',fp.read(4))[0]) # 4 bytes
spectra = []
for i in range(nrIsects*3):
spectra.append(struct.unpack('<f',fp.read(4))[0]) # 12 bytes
interaction_types = []
for i in range(nrIsects):
interaction_types.append(struct.unpack('<H', fp.read(2))[0]) # error!

-2147221231, 'ClassFactory cannot supply requested class', None, None

I am using the following code to reclassify multiple raster at once using python. after the "GP = win32com.client.Dispatch("esriGeoprocessing.GPDispatch.1")" line I receive this error:
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
GP = win32com.client.Dispatch("esriGeoprocessing.GPDispatch.1")
File "C:\Python27\ArcGIS10.1\lib\site-packages\win32com\client\__init__.py", line 95, in Dispatch
dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx)
File "C:\Python27\ArcGIS10.1\lib\site-packages\win32com\client\dynamic.py", line 108, in _GetGoodDispatchAndUserName
return (_GetGoodDispatch(IDispatch, clsctx), userName)
File "C:\Python27\ArcGIS10.1\lib\site-packages\win32com\client\dynamic.py", line 85, in _GetGoodDispatch
IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch)
com_error: (-2147221231, 'ClassFactory cannot supply requested class', None, None)
Does anyone know what the problem can be? ALso under reclassTable I am not using a .dbf but a .csv excel file. Could that be the reason? I don't know how to make a .dbf file.
Thanks ahead for any much needed help/
Kristin
code
inputDir = "c:\\tmp\\gis\\rasterReclass\\" # where all the rasters are located
outputDir = "c:\\tmp\\gis\\rasterReclass\\" # where the output rasters are to be saved
outputPrefix = "R_" # prefix of the output rasters
reclassTable = r"c:\tmp\gis\rasterReclass\reclassTable.dbf" # the reclass data table
fieldRasterName = "RASTERNAME" # column with the name of the raster
fieldRasterThreshold = "THRESHOLD" # column with the threshold value
import win32com.client, sys
GP = win32com.client.Dispatch("esriGeoprocessing.GPDispatch.1")
GP.RefreshCatalog(inputDir)
GP.RefreshCatalog(outputDir)
total = 0
ok = 0
tableRows = GP.SearchCursor(reclassTable)
tableRow = tableRows.Next()
while tableRow:
print ""
total = total + 1
rasterName = tableRow.GetValue(fieldRasterName)
threshold = tableRow.GetValue(fieldRasterThreshold)
sourceRaster = inputDir + rasterName
print "Processing " + rasterName + " with threshold value " + str(threshold)
if GP.Exists(sourceRaster):
expression = "SetNull(\"" + sourceRaster + "\" < " + str(threshold) + ", 1)"
outputRaster = outputDir + outputPrefix + rasterName
try:
GP.SingleOutputMapAlgebra(expression, outputRaster)
print "... done"
ok = ok + 1
except:
print "... " + rasterName + " failed"
else:
print rasterName + " does not exists"
tableRow = tableRows.Next()
print "--------------------------"
print str(ok) + " out of " + str(total) + " rasters sucessfully reclassified !"