0

how to create file names from a number plus a suffix??.

for example I am using two programs in python script for work in a server, the first creates a file x and the second uses the x file, the problem is that this file can not overwrite.

no matter what name is generated from the first program. the second program of be taken exactly from the path and file name that was assigned to continue the script.

thanks for your help and attention

3
  • 4
    I'm sorry to tell you that it's not entirely clear what your problem is, or even what you want to do, besides to generate filenames that somehow don't conflict and can be accessed by multiple applications (at once). Please revise your question to add more detail. Commented Oct 21, 2010 at 19:58
  • hello. well I have summarized the question simply give their answer from their point of view, my problem is I do not expect anything particular a precise answer. thanks again :-) Commented Oct 21, 2010 at 20:44
  • 1
    "I do not expect anything particular a precise answer" Then why ask? If you want any answer at all, please provide some examples. Please provide some code that shows how you want the program to look -- even if it doesn't work. Please provide some details so we know what you are talking about. Commented Oct 21, 2010 at 20:55

1 Answer 1

3

As far as I can understand you, you want to create a file with a unique name in one program and pass the name of that file to another program. I think you should take a look at the tempfile module, http://docs.python.org/library/tempfile.html#module-tempfile.

Here is an example that makes use of NamedTemporaryFile:

import tempfile
import os

def produce(text):
    with tempfile.NamedTemporaryFile(suffix=".txt", delete=False) as f:
        f.write(text)
        return f.name

def consume(filename):
    try:
        with open(filename) as f:
            return f.read()
    finally:
        os.remove(filename)

if __name__ == '__main__':

    filename = produce('Hello, world')
    print('Filename is: {0}'.format(filename))
    text = consume(filename)
    print('Text is: {0}'.format(text))
    assert not os.path.exists(filename)

The output is something like this:

Filename is: /tmp/tmpp_iSrw.txt
Text is: Hello, world
Sign up to request clarification or add additional context in comments.

Comments

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.