简体   繁体   English

如何从数字加上python后缀创建文件名

[英]how to create file names from a number plus a suffix in python

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. 例如,我正在python脚本中使用两个程序在服务器上工作,第一个创建文件x,第二个使用x文件,问题是此文件无法覆盖。

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 感谢您的帮助和关注

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 . 我认为您应该看看tempfile模块http://docs.python.org/library/tempfile.html#module-tempfile

Here is an example that makes use of NamedTemporaryFile: 这是一个使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从目录中的文件夹名称中提取后缀字符串? (蟒蛇) - How to Extract A String of the Suffix from Folder Names in a Directory? (Python) 如何创建一个包含变量名称作为字符串加上它们的值的文本文件? - How to create a text file containing variable names as string plus their values? 如何从具有相同后缀的 python 中的 substring 中提取特定数量的字符 - How to extract specific number of characters from a substring in python with same suffix 如何使用 Python 从 CSV 文件在 MySQL 中创建列名? - How to create columns names in MySQL using Python from CSV file? 从带有后缀的 Python 列表中创建子集 - Create subsets from Python list with suffix 根据Python中的文件名和后缀合并csv个文件 - Merge csv files based on file names and suffix in Python 如何在Python中创建顺序文件名 - How To Create Sequential File Names In Python 如何在python中创建任意数量的字典/列表(具有不同的名称)? - How to create an arbitrary number of dictionaries/lists (with different names) in python? 如何从列表中为数据框的特定列名附加后缀 - How to append a suffix for specific column names of a dataframe from a list 如何在Python中加一个浮点数? - How to plus one at the tail to a float number in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM