How do I read files through another file?

Do you have the filenames in a file?
Do you want pipelining, stdout/stdin teeing?

do you have the filenames in another file and want to read those filename one after the other and use the names to open the real files?????

more info needed ;)

I have a file with filenames in it like this:
file1.txt
file2.txt
file3.txt

I want to be able to read those file, and also to write to them.

meaning????

that file1.txt contains the name of file2.txt and file3.txt and so forth?

make things a bit clearer plz ;)

Suppose you have the filenames in the file "names.txt".

for line in open("names.txt")
    fi=open(line.strip())
    # now you can read the file

Here little cleaner form for slate's code (which need fi.close() in the end of for) Actually the names.txt would be better to open same way, but I think it is OK, as garbage collection surely gets it from inside the stripping generator expression (i.e. it will be automatically freed also).

for filename in (line.strip() for line in open("names.txt")):
    with open(filename) as fi:
        # now you can read the file and do not need to close it manually

Just incase your last file names are in the third file, use the result to open and read the third file.

thats it :)

OK Ill specify it a bit more.

I have a file called name.txt , in that file I have 3 lines with other filenames (each on a separate line), like:
filename1.txt
filename2.txt
filename3.txt

All these filenames also exists as files. I want to read whats in all the files and save the content from each file to a separate variable. (example save the content from filename1.txt as a, the content from filename 2 as b and the content from filename 3 as c.)

I want this to be in a function.

This should return a list [('filename1.txt', '<content>'), ('filename2.txt', '<content>'), ..]

def thefunction():
    filenames = list(x.strip() for x in list(open("name.txt", "rb")) if x.strip())
    return [(n, open(n, "rb").read()) for n in filenames]

I will have seats in all the files like: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32

I want them to be in a list

Then modify the code like this

def thefunction():
    filenames = list(x.strip() for x in list(open("name.txt", "rb")) if x.strip())
    L = [(n, open(n, "rb").read()) for n in filenames]
    return [(x, [int(z) for z in y.strip().split()]) for (x,y) in L]
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.