Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 删除文件(如果存在)。如果没有';t、 创造它_Python_File_Error Handling_Delete File - Fatal编程技术网

Python 删除文件(如果存在)。如果没有';t、 创造它

Python 删除文件(如果存在)。如果没有';t、 创造它,python,file,error-handling,delete-file,Python,File,Error Handling,Delete File,标题说明一切 我的代码: try: os.remove("NumPyResults.txt") except IOError: with open("NumPyResults.txt", 'a') as results_file: outfile = csv.writer(results_file) outfile.writerow(.......) 它在append中的原因是因为它在函数中并且被多次调用。

标题说明一切

我的代码:

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

 except IOError:

        with open("NumPyResults.txt", 'a') as results_file:
            outfile = csv.writer(results_file)
            outfile.writerow(.......)
它在append中的原因是因为它在函数中并且被多次调用。因此,每次运行程序时,我都需要一个新文件,方法是删除旧文件并编写新文件

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

我明白了


缺少文件名的例外情况是“OSError”,而不是“IOError”。 如果您得到异常,您只想通过,并且文件写入应该在try块之外

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

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

append
不按定义删除文件为什么不直接使用
open(路径“w”)
?它删除旧文件并重写它。所有这些都在一个函数中吗?每次你打电话时,文件不会被删除吗?值得一提的是,我在python3.4上得到了
FileNotFoundError
,在python2.7上得到了
OSError
try:
    os.remove("NumPyResults.txt")
except OSError:
    pass

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