Python:打开自动生成的文件

时间:2018-12-10 14:56:06

标签: windows python-2.7

作为我的大型程序的一部分,我想创建一个日志文件,并将当前时间和日期作为标题的一部分。我可以如下创建它:

public static String removeChar(String str, char target) {
    int index = str.indexOf(target);
    if (index < 0)
        return str;
    else {
        return removeChar(str.substring(0, index) + str.substring(index + 1), target);
    }
}

public static void main(String[] args) {
    String str = "0123045607890";
    System.out.println(removeChar(str, '0'));
} 

现在,我的应用程序将调用许多其他函数,因此我将需要多次打开文件,向其中写入一些输出并关闭文件。如果我简单地去,那似乎就行不通了:

123456789

或类似。那么我应该如何打开一个动态创建的txt文件,而我不知道...的实际文件名?

1 个答案:

答案 0 :(得分:0)

创建malwareLog对象时,它具有name属性,其中包含文件名。

下面是一个示例:(我的test是您的malwareLog

import random

test = open(str(random.randint(0,999999))+".txt", "w+")
test.write("hello ")
test.close()

test = open(test.name, "a+")
test.write("world!")
test.close()

with open(test.name, "r") as f: print(f.read())

您还可以在创建文件之前或之后将文件名存储在变量中。

###Before
file_name = "123"
malwareLog = open(file_name, "w")

###After
malwareLog = open(random.randint(0,999999), "w")
file_name = malwareLog.name