close

how to read a list of txt files in a folder in python

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about how to read a list of txt files in a folder in python in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

how to read a list of txt files in a folder in python?

  1. how to read a list of txt files in a folder in python?

    so you have all the files in the path folder, to read all the files in the folder you should use os or `glob' to do that.

  2. read a list of txt files in a folder in python

    so you have all the files in the path folder, to read all the files in the folder you should use os or `glob' to do that.

Method 1

Lets assume you have files in the folder path path = /home/username/foldername/

so you have all the files in the path folder, to read all the files in the folder you should use os or `glob’ to do that.

import os
path = "/home/username/foldername/"
savepath = "/home/username/newfolder/" 
for dir,subdir,files in os.walk(path):
    infile = open(path+files)
    outfile = open(savepath,'w')
    a = infile.readline().split('.')
    for k in range (0,len(a)):
        print(a[0], file=outfile, end='')
infile.close()
outfile.close
print "done"

or using glob you can do it much lesser lines of code.

import glob
path = "/home/username/foldername/"
savepath = "/home/username/newfolder/"
for files in glob.glob(path +"*.txt"):
    infile = open(files)
    outfile = open(savepath,'w')
    a = infile.readline().split('.')
    for k in range (0,len(a)):
        print(a[0], file=outfile, end='')
infile.close()
outfile.close
print "done" 

hope it might work for you.

Method 2

Thanks to Eddo Hintoso for his detailed answer, I’ve slightly tweaked it to use yield rather than return so it doesn’t need to be mapped. I’m posting it here in case it is useful to anyone else who finds this post.

import glob

files = glob.glob("data/*.txt")


def map_first_lines(file_list):
    for file in file_list:
        with open(file, 'r') as fd:
            yield fd.readline()


[print(f) for f in map_first_lines(files)]

So another way to solve this particular problem:

import glob


def map_first_lines(file_list):
    for file in file_list:
        with open(file, 'rt') as fd:
            yield fd.readline()


def merge_first_lines(file_list, filename='first_lines.txt'):
    with open(filename, 'w') as f:
        for line in map_first_lines(file_list):
            f.write("%s\n" % line)


files = glob.glob("data/*.txt")

merge_first_lines(files)

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read