[Python] read contents of a file from a list of file with os.listdir() (python)

Discussão em 'Python' iniciado por Stack, Maio 5, 2025.

  1. Stack

    Stack Membro Participativo

    I need to read the contents of a file from the list of files from a directory with os.listdir. My working scriptlet is as follows:

    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.

    Continue reading...

Compartilhe esta Página