file open on a list of filenames

This is the place for queries that don't fit in any of the other categories.

file open on a list of filenames

Postby newprogrammer » Mon Apr 22, 2013 5:30 pm

First of all I'm new on programming and python.
I'm trying to open a file from a directory and file name is not fix. it could be anything and there are many files on the directory. I create a list of the file from the directory. Now I want to open the List[0] file or first file of the directory. how could I do that. Thanks in advance.


Code: Select all
#here I create a list       
import os
L = os.listdir("data_small")


file_object = open("data_small/L[1]","r")    #<--------- here needs change
#some code goes here
file_object.close()
Last edited by Yoriz on Mon Apr 22, 2013 5:57 pm, edited 3 times in total.
Reason: Changed to a more descriptive title
newprogrammer
 
Posts: 4
Joined: Mon Apr 22, 2013 5:18 pm

Re: file open in python

Postby setrofim » Mon Apr 22, 2013 5:50 pm

data_small, not small_data.

(also, please use [code] tags when posting code).
setrofim
 
Posts: 285
Joined: Mon Mar 04, 2013 7:52 pm

Re: file open on a list of filenames

Postby newprogrammer » Mon Apr 22, 2013 11:45 pm

Thanks setrofim, I edit thoes but that's not a main problem.
newprogrammer
 
Posts: 4
Joined: Mon Apr 22, 2013 5:18 pm

Re: file open on a list of filenames

Postby snippsat » Tue Apr 23, 2013 12:32 am

When you use os.listdir() it give you back a list of filenames.
The first file is L[0] not data_small/L[1]

os.listdir() give back only filenames so If run .py file from other folder than data_small you need to join path and filename.
Code: Select all
import os

path = r"c:\test"
file_lst = os.listdir(path)
with open(os.path.join(path, file_lst[0])) as file_object:
    print file_object.name

Module glob give you back full path.
Then it can look like this.
Code: Select all
from glob import glob

with open(glob(r'c:\test\*')[0]) as file_object:
    print file_object.name
User avatar
snippsat
 
Posts: 85
Joined: Thu Feb 21, 2013 12:04 am

Re: file open on a list of filenames

Postby newprogrammer » Fri Apr 26, 2013 3:16 pm

Thanks for your help.
newprogrammer
 
Posts: 4
Joined: Mon Apr 22, 2013 5:18 pm


Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 6 guests