0

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.

5
  • 2
    Make sure to escape those backslashes. Commented Jan 13, 2010 at 17:59
  • 4
    Have you read about the return statement yet? docs.python.org/reference/… Commented Jan 13, 2010 at 18:00
  • 2
    Use os.path.join to join paths. Commented Jan 13, 2010 at 18:01
  • 1
    Also, these are functions, not classes. Perhaps you should fix your question title. Commented Jan 13, 2010 at 18:02
  • This guy is a noob. Someone please post code using yield keyword. I do not think s[he] can write it independently just yet. Commented Jan 13, 2010 at 18:03

2 Answers 2

1
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:\\')]
Sign up to request clarification or add additional context in comments.

1 Comment

or ... dirList = ('c:\\', 'y:\\', 'z:\\') - tuple is all that is needed return (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.
1

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

2 Comments

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():
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.

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.