1

The file is a device under /dev. I don't want to mess things up so if the file does not exist, I should not create it. How to handle this in Python?

I hope this problem be solved by open method. That is, it should throw an IOError like mode "r" when the file does not exist. Don't redirect the question to "check if a file exists".

bfrgzju
  • 175
  • 1
  • 9

3 Answers3

3

There's two ways to do this. Either

from os.path import exists
if exists(my_file_path):
    my_file = open(my_file_path, 'w+')

if you need to trigger things based on the file existing, that's the best way.

Otherwise, just do open(file_path, 'r+')

Morgan Thrapp
  • 9,748
  • 3
  • 46
  • 67
1
import os

if os.path.exists(dev):
    fd = os.open(dev, os.O_WRONLY) # or open(dev, 'wb+')
    ...

Also check How to perform low level I/O on Linux device file in Python?

Community
  • 1
  • 1
fferri
  • 18,285
  • 5
  • 46
  • 95
-1

Here is a simple python script that shows the files in a directory, where their file is and whether the real file exists or not

import os

def get_file_existency(filename, directory):
 path = os.path.join(directory, filename)
 realpath = os.path.realpath(path)
 exists = os.path.exists(path)
 if exists:
   file = open(realpath, 'w')
 else:
   file = open(realpath, 'r')
Praneeth
  • 902
  • 2
  • 11
  • 25