>>> from os import *
>>> a = []
>>> a = listdir('.')
>>> f = open(a[0],'r')

Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
f = open(a[0],'r')
TypeError: an integer is required

doesn't work, please help me

One thing, you can not open a directory, so you should test that it is a file.

import os
a = []
a = os.listdir('.')
for t in a:
    if os.path.isfile(t):
        f = open(t,'r')
        print t, "opened"
        f.close()
    else:
        print "     ", t, "not a file"

Also, if you are not using Idle for writing code, http://www.annedawson.net/Python_Editor_IDLE.htm that is the editor/IDE that you want to start with. You can choose from several other options once you know what you want in an IDE.

Thank you for your answer. But I want to open the first file in a directory.

As woooee already mentioned, don't use the Python Shell (has those screwy looking >>> prompts) for writing programs. The Shell is only used for testing small parts of code.

You can modify woooee's code ...

import os
a = []
a = os.listdir('.')
for t in a:
    if os.path.isfile(t):
        f = open(t,'r')
        print t, "opened"
        data_str = f.read()
        # do something with the data string later ...
        f.close()
        # break here if you only want the first file
        break
    else:
        print "     ", t, "not a file"

# now process your data string

Thank you

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.