Get name of file from directory into variable

L

loial

In a unix shell script I can do something like this to look in a
directory and get the name of a file or files into a variable :

MYFILE=`ls /home/mydir/JOHN*.xml`


Can I do this in one line in python?
 
A

Alex Willmer

In a unix shell script I can do something like this to look in a
directory and get the name of a file or files into a variable :

MYFILE=`ls /home/mydir/JOHN*.xml`

Can I do this in one line in python?

Depends if you count imports.

import glob
my_files = glob.glob('/home/mydir/JOHN*.xml')

Regards, Alex
 
S

Steven W. Orr

In a unix shell script I can do something like this to look in a
directory and get the name of a file or files into a variable :

MYFILE=`ls /home/mydir/JOHN*.xml`


Can I do this in one line in python?

Sorry, but I just can't help myself.

Yeah, it's one shell line, but why the extra process, setup of pipes,
teardown, and all the rest when you can just say

MYFILE=/home/mydir/JOHN*.xml

After all, your way just starts a subshell which runs ls in a grandchild
process and creates a pipe to read back what the subshell writes. All the
subhell does is to run ls on what the shell globs. And without any options to
the ls command, you're just as well off by using echo instead of ls.

MYFILE=`echo /home/mydir/JOHN*.xml`

Since echo is probably a builtin, you'd be creating a child but no grandchild.

Other than that, the use of glob in python answers your question well (unless
someone wants to write up how to do it in python by use of the subprocess
module along with the glob module...)

--
Time flies like the wind. Fruit flies like a banana. Stranger things have .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net


-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.10 (GNU/Linux)
Comment: Using GnuPG with Fedora - http://enigmail.mozdev.org/

iEYEARECAAYFAkxZiswACgkQRIVy4fC+NyTVQQCeIPJaL+YURb7Zcq14hyULrH5E
EHwAoI0vEb6U6k6My7KgRgVKLzKDBZ+g
=zhLM
-----END PGP SIGNATURE-----
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top