views:

66

answers:

2

In code(pseudo) like this

def path():
    dirList = ['c:\\', 'y:\\', 'z:\\']
    home_folder = 'peter.txt'
    complete = [s + home_folder for s in dirList]
    print complete

def fileWrite():
    filename = 'c:\peter.txt'
    text = 'Hello World'
    file = open(filename, 'w')
    file.write(text)
    file.close()

I can make both work. I want all the items from the first to be iterated and run in the second. I am not entirely sure how to do that. Any help, much appreciated.

+1  A: 

If I understand question correclty - you can add additional parameter to fileWrite like fileWrite(filename) and simply iterate over 'complete' sequence.

bluszcz
Yes, clearly. The complete object is a list, so if he just returns it from path(), he should be able to write for each_path in path():
Adam Crossland
One could call fileWrite from the first function. If the two are to communicate through a return, they better use an iterator and not a list - saves space = good practice.
Hamish Grubijan
+1  A: 
import os

def paths(filename):
    dirList = ['c:\\', 'y:\\', 'z:\\']
    complete = [os.path.join(s, filename) for s in dirList]
    return complete

def fileWrite():
    for each_file in paths('c:\\peter.txt'):
        text = 'Hello World'
        file = open(each_file, 'w')
        file.write(text)
        file.close()

Or, as Ipthnc points out below, the paths function can be shortened to:

def paths(filename):
    return [os.path.join(s, filename) for s in ('c:\\', 'y:\\', 'z:\\')]
Adam Crossland
or ...dirList = ('c:\\', 'y:\\', 'z:\\') - tuple is all that is neededreturn (os.path.join(s, filename) for s in dirList) - a generator will do because it is used in for loop only.Sorry to be be a pain, just wanted to show cool stuff.
Hamish Grubijan