delete a file if it exists. if it doesn't, create it

  • Last Update :
  • Techknowledgy :

The exception I get for a missing filename is 'OSError', not 'IOError'. And if you get the exception, you just want to pass, and the file writing should be outside the try block.

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

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

Suggestion : 2

In this article we will discuss how to remove a file if only it exists and how to handle other types of exceptions using os.remove() & os.ulink().,As os.remove() can throw OSError if given path don’t exists, so we should first check if file exists then remove i.e. , Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models. ,A file don’t exists at given path. Error message will be like, [WinError 2] The system cannot find the file specified FileNotFoundError: [Errno 2] No such file or directory

python ‘s os module provides a function to remove the file i.e.

os.remove(path_of_file)

For example,

import os

# Remove a file
os.remove('/home/somedir/Documents/python/logs')

As os.remove() can throw OSError if given path don’t exists, so we should first check if file exists then remove i.e.

import os

filePath = '/home/somedir/Documents/python/logs';

# As file at filePath is deleted now, so we should check
if file exists or not not before deleting them
if os.path.exists(filePath):
   os.remove(filePath)
else:
   print("Can not delete the file as it doesn't exists")

python provides an another function in os module to remove files i.e.

os.unlink(filePath)

import os

# Handle errors
while calling os.ulink()
try:
os.ulink(filePath)
except:
   print("Error while deleting file ", filePath)

Suggestion : 3

Right click the bad file and click Add to Archives. Then in the options select to delete original file after compression.,Right click the bad file and click Add to Archives. Then in the options select to delete original file after compression. ,Leave other options same and proceed. Bad file will be deleted and a compressed file will be created in its place.,Leave other options same and proceed. Bad file will be deleted and a compressed file will be created in its place.

Launch Command prompt as admin and modify the below to your needs.

del "\\?\<full path to file>"

Example:

del "\\?\C:\Users\Username\Desktop\filename."

Suggestion : 4

09/24/2021

You can't delete a file if the file name includes an invalid name. For example, the file name has a trailing space or a trailing period, or the file name is made up of a space only. To resolve this issue, use a tool that uses the appropriate internal syntax to delete the file. You can use the "\\?\" syntax with some tools to operate on these files. Here's an example:

del "\\?\c:\<path_to_file_that contains a trailing space.txt>"

In this situation, you can use the Subinacl utility with the /onlyfile switch (this utility is included in the Resource Kit) to change ownership and permissions on a file that's otherwise inaccessible. Here's an example:

subinacl /onlyfile "\\?\c:\<path_to_problem_file>" /setowner= domain\administrator /grant= domain\administrator=F

Suggestion : 5

If the file doesn’t exist, the is_file() method returns False. Otherwise, it returns True.,The following example shows how to use the Path class from the pathlib module to check if the readme.txt file exists in the same folder of the program:,If the file exists, the exists() function returns True. Otherwise, it returns False.,To do it, you can use the exists() function from the os.path module or is_file() method from the Path class in the pathlib module.

os.path.exists() function

.wp - block - code {
      border: 0;
      padding: 0;
   }

   .wp - block - code > div {
      overflow: auto;
   }

   .shcb - language {
      border: 0;
      clip: rect(1 px, 1 px, 1 px, 1 px); -
      webkit - clip - path: inset(50 % );
      clip - path: inset(50 % );
      height: 1 px;
      margin: -1 px;
      overflow: hidden;
      padding: 0;
      position: absolute;
      width: 1 px;
      word - wrap: normal;
      word - break: normal;
   }

   .hljs {
      box - sizing: border - box;
   }

   .hljs.shcb - code - table {
      display: table;
      width: 100 % ;
   }

   .hljs.shcb - code - table > .shcb - loc {
      color: inherit;
      display: table - row;
      width: 100 % ;
   }

   .hljs.shcb - code - table.shcb - loc > span {
      display: table - cell;
   }

   .wp - block - code code.hljs: not(.shcb - wrap - lines) {
      white - space: pre;
   }

   .wp - block - code code.hljs.shcb - wrap - lines {
      white - space: pre - wrap;
   }

   .hljs.shcb - line - numbers {
      border - spacing: 0;
      counter - reset: line;
   }

   .hljs.shcb - line - numbers > .shcb - loc {
      counter - increment: line;
   }

   .hljs.shcb - line - numbers.shcb - loc > span {
      padding - left: 0.75 em;
   }

   .hljs.shcb - line - numbers.shcb - loc::before {
      border - right: 1 px solid #ddd;
      content: counter(line);
      display: table - cell;
      padding: 0 0.75 em;
      text - align: right; -
      webkit - user - select: none; -
      moz - user - select: none; -
      ms - user - select: none;
      user - select: none;
      white - space: nowrap;
      width: 1 % ;
   }
from os.path
import exists

file_exists = exists(path_to_file) Code language: JavaScript(javascript)

Path.is_file() method

from pathlib
import Path

path = Path(path_to_file)

path.is_file() Code language: JavaScript(javascript)

First, import the os.path standard library:

import os.pathCode language: JavaScript(javascript)

However, it’s not the case, you need to pass the full file path of the file. For example:

/path/to / filename

The following example uses the exists() function to check if the readme.txt file exists in the same folder as the program:

import os.path

file_exists = os.path.exists('readme.txt')

print(file_exists) Code language: JavaScript(javascript)

Suggestion : 6

Last Updated : 29 Apr, 2022

Syntax:

file_exists($path)

The file path doesn 't exists in GeeksforGeeks directory

Output:

1

The file path doesn 't exists in GeeksforGeeks directory

Given https: //www.geeksforgeeks.org doesn't exists in GeeksforGeeks Portal

Output:

1