Reading file from a list from anos.dirlist

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

Reading file from a list from anos.dirlist

Postby lovecodecakes » Sat Feb 23, 2013 12:52 pm

Is there any way to read() an element that is actualy a file which is read from a list pointing to a os.listdir

Code: Select all
os.listdir("C:\Users\Hero\Desktop")


Code: Select all
liklist.index('New Text Document.txt')
Out[24]: 10

f=codecs.open(liklist[10],'rU').read()
---------------------------------------------------------------------------
IOError                                   Traceback (most recent call last)
<ipython-input-25-68f82192dc6f> in <module>()
----> 1 f=codecs.open(liklist[10],'rU').read()

C:\WinPython-64bit-2.7.3.3\python-2.7.3.amd64\lib\codecs.pyc in open(filename, mode, encoding, errors, buffering)
    879             # Force opening of the file in binary mode
    880             mode = mode + 'b'
--> 881     file = __builtin__.open(filename, mode, buffering)
    882     if encoding is None:
    883         return file

IOError: [Errno 2] No such file or directory: 'New Text Document.txt'

NOTE: The file exists
lovecodecakes
 
Posts: 56
Joined: Mon Feb 11, 2013 8:19 pm

Re: Reading file from a list from anos.dirlist

Postby Yoriz » Sat Feb 23, 2013 1:14 pm

Yes you should be able to do that if i can decipher your question correctly.

print the current working directory
Code: Select all
os.getcwd()

and the value of
Code: Select all
liklist[10]

are those combined the location of the file your trying to open?
New Users, Read This
Join the #python-forum IRC channel on irc.freenode.net!
Spam topic disapproval technician
Windows7, Python 2.7.4., WxPython 2.9.5.0., some Python 3.3
User avatar
Yoriz
 
Posts: 827
Joined: Fri Feb 08, 2013 1:35 am
Location: UK

Re: Reading file from a list from anos.dirlist

Postby lovecodecakes » Sat Feb 23, 2013 1:42 pm

yes.
hey I found it just now, using os.path.abspath(,) I can use the filename and path fully and read it to file.
Will catch up on getcwd didn't know about that.

Yoriz wrote:are those combined the location of the file your trying to open?
lovecodecakes
 
Posts: 56
Joined: Mon Feb 11, 2013 8:19 pm


Return to General Coding Help

Who is online

Users browsing this forum: Google [Bot], W3C [Linkcheck] and 2 guests

cron