Question: read contents of a file from a list of file with os.listdir() (python)
0
gravatar for ahmedakhokhar
2.9 years ago by
ahmedakhokhar110
Belgium
ahmedakhokhar110 wrote:

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.

os.listdir python • 16k views
ADD COMMENTlink modified 2.9 years ago by RamRS24k • written 2.9 years ago by ahmedakhokhar110

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

ADD REPLYlink written 2.9 years ago by WouterDeCoster42k
0
gravatar for jonasmst
2.9 years ago by
jonasmst290
Norway/Oslo
jonasmst290 wrote:

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 COMMENTlink modified 2.9 years ago • written 2.9 years ago by jonasmst290
3

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 REPLYlink written 2.9 years ago by WouterDeCoster42k

Nice, didn't know that

ADD REPLYlink written 2.9 years ago by jonasmst290
Please log in to add an answer.

Help
Access

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.
Powered by Biostar version 2.3.0
Traffic: 1723 users visited in the last hour