user1801279
user1801279

Reputation: 1783

getting a filename in python

I have the following code to get a list of file names in a particular directory

import sys,os

data_files = [x[2] for x in os.walk(os.path.dirname(sys.argv[0]))]
print data_files

the output is something like

[['bar.py',  'foo.py', 'foo.pyc', 'fooBar', 'fooBar.py', 'tar.py', 'tar.pyc']]

I want to parse this list and pass only a particular filename to another function

for example : I want to parse the list?( is it a list?) above and pass only tar.py to another function , ie the name tar , so as another function can use it like

import filename ( in this case tar)

I am new to python and tried a lot of list parsing stuff but could not extract the name . any help would be appreciated

I am using python 2.7

Thank you for your time

EDIT:

I figured out how to parse the list

data_files = [x[2] for x in os.walk(os.path.dirname(sys.argv[0]))]
hello = data_files[0]
print hello[0].split(".")[0]

the problem is when I try assigning the file name to a variable like

var = hello[0].split(".")[0]

and use import var

but I am not sure if python allows importing modules like this because it does not consider var as a variable but a module name . how can I overcome this

Upvotes: 0

Views: 269

Answers (2)

user1632861
user1632861

Reputation:

If you know which index your element is at, you can do file_list[index_of_your_element].split('.')[0], for example:

file_list = ['bar.py',  'foo.py', 'foo.pyc', 'fooBar', 'fooBar.py', 'tar.py', 'tar.pyc']
print l[5].split('.')[0] == 'tar'

Will print true. Your question is kinda confusing, what do you know about the element, and how do you want to use it?

Upvotes: 0

oathead
oathead

Reputation: 462

I'm a little confused on what you mean by list parsing. It is a list and if you want to remove all the file extensions you can do it with a list comprehension and split as fastreload suggested.

new_list = [x.split('.')[0] for x in data_files]

If you need to step through the list looking at each file you can do that with

for file in data_files:
    your code goes here

Upvotes: 2

Related Questions