删除文件(如果存在)。如果没有,请创建它

Delete a file if it exists. If it doesn't, create it

标题说明了一切。

我的代码:

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

 except IOError:

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

它在追加中的原因是因为它在一个函数中并且被调用了很多次。所以每次我 运行 程序时我都想要一个新文件,通过删除旧文件并编写新文件。

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

我明白了

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

我得到的丢失文件名的异常是 'OSError',而不是 'IOError'。 而如果你得到异常,你只想通过,写文件应该在try块之外。

try:
    os.remove("NumPyResults.txt")
except OSError:
    pass

with open("NumPyResults.txt", 'a') as results_file:
    results_file.write('hi\n')