views:

62

answers:

1

hello. 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  A: 

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
Bernd Petersohn