0

I have 10 data in txt format: a1.txt,a2.txt,...,a10.txt and I want to load them one by one in a for loop.

To load a file I use

data = read_data('a1.txt');

but I am not sure how to use it in a for loop.

1
  • Start by asking yourself, what part should change on each iteration of the loop? Commented Oct 22, 2019 at 23:28

3 Answers 3

2

Search for files inside path that end with .txt

from os import listdir
from os.path import isfile, join
mypath='/tmp'

files = [f for f in listdir(mypath) if isfile(join(mypath, f)) and f.endswith('.txt')]

Another approach with pathlib (python 3.4+). It recognizes also the a for matching:

from pathlib import Path

files = [str(f) for f in Path(mypath).iterdir() if f.match("a*.txt")]
Sign up to request clarification or add additional context in comments.

Comments

1

Use the range() function to generate a sequence of numbers, and then use string formatting to assemble the filename:

for number in range(1, 11):
    filename = 'a%d.txt' % number
    data = read_data(filename)

Comments

1

If you have the txt files in a folder you could read the entire folder and loop through the txt files in it.

   import glob 
   folder_path = 'path/to/the/folder'

   for filename in glob.glob(folder_path, '*.txt')):
       #Your process for each file

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.