Starwarsfan2099
Starwarsfan2099

Reputation: 144

Python: Extracting data inside first set of quotes?

Ok, I have a python function that returns this EDIT[ TK open file dialog]:

<open file u'C:/WINDOWS/system32/calc.exe', mode 'rb' at 0x0218B390>

I am writing a debugger in TK, and I have the debugger open and launch a file. How can I extract just whats inside the first set of quotes? ('C:/WINDOWS/system32/calc.exe') The location inside the quotes will change, so I can't just set the location I want.

Upvotes: 0

Views: 210

Answers (3)

hiro protagonist
hiro protagonist

Reputation: 46849

it looks like you are printing out the FileObject of an open file. if that is the case: a FileObject also has a name attribute that just returns the path to the file

with open('/tmp/test.txt', 'w') as file:
    print(file)
    print(file.name)
# <_io.TextIOWrapper name='/tmp/test.txt' mode='w' encoding='UTF-8'>
# /tmp/test.txt

Upvotes: 3

LetzerWille
LetzerWille

Reputation: 5658

st = "<open file u'C:/WINDOWS/system32/calc.exe', mode 'rb' at 0x0218B390>".split()[2]
import ast
col2 = ast.literal_eval(st)[0]
print(col2)
C:/WINDOWS/system32/calc.exe

Upvotes: -1

Cody Bouche
Cody Bouche

Reputation: 955

without regex

data = '<open file u\'C:/WINDOWS/system32/calc.exe\', mode \'rb\' at 0x0218B390>'
print data.split('\'')[1]

with regex

import re

data = '<open file u\'C:/WINDOWS/system32/calc.exe\', mode \'rb\' at 0x0218B390>' 
print re.findall('\'(.*?)\'', data)[0]

Upvotes: 0

Related Questions