read contents of a file from a list of file with os.listdir() (python)
1
0
Entering edit mode
7.3 years ago
ahmedakhokhar ▴ 150

I need to read the contents of a file from the list of files from a directory with os.listdir, my working scriptlet is following:

import os

path = "/Users/Desktop/test/"

for filename in os.listdir(path):
     with open(filename, 'rU') as f:
         t = f.read()
         t = t.split()
         print(t)

print(t) gives me all the contents from all the files at once present in the directory (path).

But I like to print the contents on first file, then contents of the second and so on, until all the files are read from in dir.

Please guide ! Thanks.

python os.listdir • 31k views
ADD COMMENT
0
Entering edit mode

This is a loop sequentially opening each file and printing that. How is this different from what you want?

ADD REPLY
0
Entering edit mode
7.3 years ago
jonasmst ▴ 410

You can use f.readline() to read one line at a time:

import os

path = "/Users/Desktop/test/"

# Read every file in directory
for filename in os.listdir(path):
    with open(filename, "r") as f:
        # Read each line of the file
        for line in f.readlines():
            print line.split()
ADD COMMENT
3
Entering edit mode

f.readlines() will load the file in a list entirely, which depending on the size of the file and the available memory may not be desirable.

Opening a file returns an iterator, making .readlines() unnecessary:

path = "/Users/Desktop/test/"
# Read every file in directory
for filename in os.listdir(path):
    with open(filename, "r") as f:
        # Read each line of the file
        for line in file:
            print line.split()
ADD REPLY
0
Entering edit mode

Nice, didn't know that

ADD REPLY

Login before adding your answer.

Traffic: 2502 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6