-2

The first part of my project is to create a loop in which it reads an unknown amount of text files. I am confused how to approach this as my past projects I have entered the entry of a file specifically e.g.

for line in open('text1.txt')

How do I make it so if there's e.g. 10 files generated while it checks my code my code will actually read through 10 files? I was thinking of

for line in range(0, _input_ + 1_
  for line in open ???

But I have no luck figuring out what to do. Help would be highly appreciated, thanks :D

  • these files have to have something in common, like a parent folder or something.. Look at the `os` module. – Ma0 Aug 22 '17 at 12:58
  • They're all appending files, like if there's 6 files it will be text1.txt, text2.txt, text3.txt, text4.txt, text5.txt, text6.txt – TheBestUser Aug 22 '17 at 12:59
  • have a look at this https://stackoverflow.com/questions/10377998/how-can-i-iterate-over-files-in-a-given-directory – mbieren Aug 22 '17 at 13:00
  • Possible duplicate of [How can I iterate over files in a given directory?](https://stackoverflow.com/questions/10377998/how-can-i-iterate-over-files-in-a-given-directory) – Diziet Asahi Aug 22 '17 at 13:18

1 Answers1

-1

You can use something like this where ROOTDIR is a parent directory of your files:

# path to parent folder of your files
ROOTDIR = '/home/your_name/parent_folder'

for subdir, dirs, files in os.walk(ROOTDIR):
    name = str(subdir).split('/')[-1]
    print(subdir)
    for f in files:
        print('Working on file:', f)
        SOURCE = str(subdir) + '/' + str(f)

        # load text
        text = open(SOURCE, encoding='utf-8').readlines()

Novak
  • 2,143
  • 1
  • 12
  • 22