删除文件(如果存在)。如果没有,创造我

2024-04-26 12:40:01 发布

您现在位置:Python中文网/ 问答频道 /正文

标题说明一切。

我的代码:

 try:
        os.remove("NumPyResults.txt")

 except IOError:

        with open("NumPyResults.txt", 'a') as results_file:
            outfile = csv.writer(results_file)
            outfile.writerow(.......)

之所以在append中,是因为它在一个函数中,被调用了很多次。所以我希望每次运行程序时都有一个新文件,删除旧文件并编写新文件。

但是,这不会创建新文件。我还在运行的目录中创建了该文件,但它也不会删除它。

我明白了

WindowsError: [Error 2] The system cannot find the file specified: 'NumPyResults.txt'

Tags: 文件代码txt标题oswithopenresults