0

>>> 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

3
Contributors
4
Replies
5
Views
7 Years
Discussion Span
Last Post by WOPR
Featured Replies
  • 1

    One thing, you can not open a directory, so you should test that it is a file. [CODE]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" [/CODE] Also, if you … Read More

  • 1

    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 ... [code]import os a = [] a = os.listdir('.') for t in a: if os.path.isfile(t): f … Read More

1

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.

Edited by woooee: n/a

0

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

1

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

Edited by vegaseat: data

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.