简体   繁体   中英

Reading in multiple files in directory using python

I'm trying to open each file from a directory and print the contents, so I have a code as such:

import os, sys

def printFiles(dir):
    os.chdir(dir)
    for f in os.listdir(dir):
        myFile = open(f,'r')
        lines = myFile.read()
        print lines
        myFile.close()

printFiles(sys.argv[1])

The program runs, but the problem here is that it is only printing one of the contents of the file, probably the last file that it has read. Does this have something to do with the open() function?

Edit: added last line that takes in sys.argv. That's the whole code, and it still only prints the last file.

There is problem with directory and file paths.

Option 1 - chdir:

def printFiles(dir):
    os.chdir(dir)
    for f in os.listdir('.'):
        myFile = open(f,'r')
        # ...

Option 2 - computing full path:

def printFiles(dir):
    # no chdir here
    for f in os.listdir(dir):
        myFile = open(os.path.join(dir, f), 'r')
        # ...

But you are combining both options - that's wrong.

This is why I prefer pathlib.Path - it's much simpler:

from pathlib import Path

def printFiles(dir):
    dir = Path(dir)
    for f in dir.iterdir():
        myFile = f.open()
        # ...

The code itself certainly should print the contents of every file. However, if you supply a local path and not a global path it will not work.

For example, imagine you have the following folder structure:

./a
./a/x.txt
./a/y.txt
./a/a
./a/a/x.txt 

If you now run

printFiles('a')

you will only get the contents of x.txt , because os.listdir will be executed from within a , and will list the contents of the internal a/a folder, which only has x.txt .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM