I have the following code to copy a section of a text file to a new, temporary file. I am trying to create the temp file in the same directory as the file that is being copied. All of the print statements are to see how far it runs before crashing, pdb prints 1 and then give the error that is screencapped below the code.
def copymp(mptfile):
print 1
temp = os.path.dirname(mptfile) + '/mpdata.tmp'
print 2
mpfile = open(temp, 'w')
print 3
copyline = False
for line in mptfile:
print 4
if line.startswith('MP'):
copyline = True
print 5
if copyline:
print 6
print>>mpfile, line
copyline = False
mpfile.seek(1)
return None
The parameter to
os.path.dirname()must be a string, but you are apparently passing in a file object. (Is this intended?) Tryinstead.
(Side note: You should look closely at the traceback you get. The traceback shows in which line the error is occurring – no need for the print statements to isolate it. In this case, you can see it’s the call to
os.path.dirname()that is failing, so you should check its documentation to diagnose the problem.)