-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
0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

you can try: import os import pandas as pd data_set = pd.DataFrame() for root, dirs, files in os.walk("<your source folder>"): 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("<your destination folder>/tx.txt", index=False, header=False)
@Loku Did you make this comment on the wrong post? It doesn't seem to be related.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.