About file in python
In Python, a file is a named location on disk that stores data. A file can be a text file, a binary file, or a script. You can open, read, write, and close files using Python’s built-in ‘open()’ function and the related file object.
When you open a file, you specify the name of the file and the mode in which you want to open it. The mode can be ‘r’ for reading, ‘w’ for writing, or ‘a’ for appending.
For example, the following code opens a file named “example.txt” in read mode:
f = open("example.txt", "r")
You can then read the contents of the file using the ‘read()’ method and close the file using the ‘close()’ method:
contents = f.read()
f.close()
You can also use os.path module method like ‘os.path.exists()’, ‘os.path.isfile()’ and ‘os.path.isdir()’ to check if the file or folder exist in the given path.
It’s also important to note that in Python, it’s considered good practice to use the with statement when working with files, this will automatically close the file after you’re done with it and also can handle any exceptions that might arise while working with the file.
Check whether a file exist without exceptions
In Python, you can use the ‘os.path’ module to check if a file exists without raising an exception. The ‘os.path.exists()’ function returns ‘True’ if the file specified in the path exists and ‘False’ if it does not. For example:
import os
if os.path.exists("path/to/file"):
print("File exists.")
else:
print("File does not exist.")
You can also use ‘os.path.isfile()’ function to check if given path is an existing regular file.
import os
if os.path.isfile("path/to/file"):
print("Its a file.")
else:
print("Its not a file.")
You can also use ‘os.path.isdir()’ function to check if given path is an existing directory.
import os
if os.path.isdir("path/to/folder"):
print("Its a folder.")
else:
print("Its not a folder.")