2

I'm working on a function that reads multiple files (from their filenames in a single file) one-by-one. I set up the means of getting the amount of filenames in the file, but I'm not sure what I should use in the loop sequence. Here is where I am at now:

with open('userdata/addedfiles', 'r') as read_files:
        number_of_files = sum(1 for _ in read_files)

    print(number_of_files, "files added")
    print("File contents: \n")

    # get individual filenames in file and
    # read them one by one

    for x in range(number_of_files):
        # hmm...

Any suggestions on what to use here? Thanks.

tolbiac
  • 67
  • 1
  • 6
  • 2
    `number_of_files = sum(1 for _ in read_files)` is equal to `number_of_files = len(read_files)` .... right? – Jose Ricardo Bustos M. May 04 '15 at 23:40
  • 1
    @JoseRicardoBustosM. `'_io.TextIOWrapper' has no len()` – Stefan Pochmann May 04 '15 at 23:44
  • You are seeing the problem in reverse. 1) Find an easy way to iterate all the filenames and 2) read its content and print it. http://stackoverflow.com/questions/3207219/how-to-list-all-files-of-a-directory-in-python – Joe May 04 '15 at 23:46

3 Answers3

4

You have the right idea, but with your current setup you will be looping through the items in the input file a few times more than necessary. Lets try something like this:

with open('userdata/addedfiles', 'r') as read_files:
    file_lines = read_files.readlines()
    # print the length of the lines from the input file
    print(len(file_lines), "files added")

    # do stuff per line (which in your case is a file name)
    for file_name in file_lines:
        print(file_name.strip())
2

I'm not really sure of what you're trying to achieve but the code below will open all files inside userdata/addedfiles/ and print the file name and the content line by line.

You can use glob

import glob
for file in glob.glob("userdata/addedfiles/*"):
    print file
    myfile = open(file,"r")
    lines = myfile.readlines()
    for line in lines:
         print line.strip();
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
1

Not clear on why you need to get the number of files in the main file but why not just:

with open('userdata/addedfiles', 'r') as read_files:
    for infile in read_files:
        with open(infile) as infile2:
             # Do something with contents
ODiogoSilva
  • 2,394
  • 1
  • 19
  • 20