문제

I have the following directories and subdirectories with txfiles in it. I want to access them for reading the lines. But this does not work. can you help me out here?

main directory: 2009

sub directory: movies, albums, songs

each of these directory contains text files. I want to read through each lines of these text files

my pseudocode is as folllows

x = os.listdir("2009")

Now, x will be a list of [movies, albums, songs]

for el in x:
  os.system("ls 2009/el")
  for lines in os.popen(2009/el"):
       print lines
도움이 되었습니까?

해결책

If all you want it accessing the line, (eg. printing them out as in the question), I don't think you need os.popen.

The code you have given doesn't work because it even has syntax errors. (unmatched double quotes)

Here is some sample code which does what you're asking for.

>>> dirname='2009' #or the full path.
>>> for filename in os.listdir(dirname):
...     with open(os.path.join(dirname, filename)) as f:
...         for line in f.readlines():
...             print line
...

I hope this helps.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top