-3

How can I read multiple txt file from a single folder in Python?

I tried with the following code but it is not working.

import glob

import errno

path = '/home/student/Desktop/thesis/ndtvnews/garbage'

files = glob.glob(path)

for name in files:
    try:
        with open(name) as f:
            print name

        for line in f:
            print line,

        f.close()

    except IOError as exc:
        if exc.errno != errno.EISDIR:
            raise
SUB0DH
  • 5,130
  • 4
  • 29
  • 46

1 Answers1

1

Your glob isn't correct. You should add a /* to the end of your path to select all files (or directories) in your path, and then check if they are files with os.path.isfile. Something like:

from os.path import isfile
files=filter(isfile,glob.glob('%s/*'%path))

You also have an issue with the actual opening. When your with statement ends, the file is closed and f is no longer accessible. Anything you do with the file should be under the with statement. And you shouldn't explicitly close it.

Chris
  • 1,613
  • 17
  • 24
  • you can try: import os import pandas as pd data_set = pd.DataFrame() for root, dirs, files in os.walk(""): for file in files: if file.endswith('.txt'): df = pd.read_csv(root + "/" + file, header=None) data_set = pd.concat([data_set, df]) data_set.to_csv("/tx.txt", index=False, header=False) – Loku May 05 '21 at 00:24
  • @Loku Did you make this comment on the wrong post? It doesn't seem to be related. – Chris May 05 '21 at 00:26