how to detect file if exist in python [duplicate] - python

This question already has answers here:
How do I check whether a file exists without exceptions?
(40 answers)
Closed 3 years ago.
how can i detect if a specifics files exist in directory ?
example:
i want to detect if (.txt) files exist in directory (dir)
i tried with this :
import os.path
from os import path
def main():
print ("file exist:"+str(path.exists('guru99.txt')))
print ("File exists:" + str(path.exists('career.guru99.txt')))
print ("directory exists:" + str(path.exists('myDirectory')))
if __name__== "__main__":
main()
but all this functions you must to insert the complete file name with format(.txt)
Thank you !

from glob import glob
files = glob('*.txt')
print(len(files)) # will return the number of .txt files in the dir
print(files) # will return all the .txt files in the dir

to check if a specific file exists:
import os
os.path.exists(path_to_file)
will return True if it exists, False if not
to check if ANY .txt files exist:
import glob
if glob.glob(path_to_files_'*.txt'):
print('exists')
else:
print('doesnt')

Related

How to move files based on their names with python? [duplicate]

This question already has answers here:
Moving all files from one directory to another using Python
(11 answers)
Closed 6 months ago.
I have a folder with a lot of tutorial links, so I wanted to create a script that reads the file name and for instance, if the file has in its name the word "VBA" or "Excel" it would create the folder Excel and send to it. The same would happen with files containing the word "python".
The code is running, but nothing happens and the files still in the same directory. Does anyone have an idea of what I'm doing wrong?
Here is what I have in the folder, all files are links to youtube tutorials or websites:
Please see my code below:
import os
import shutil
os.chdir(r"C:\Users\RMBORGE\Desktop\Useful stuff")
path = r"C:\Users\RMBORGE\Desktop\Useful stuff\Excel"
for f in os.listdir():
if "vba" in f:
shutil.move(os.chdir,path)
Try this
import os
import shutil
path_to_files = 'some path'
files = os.listdir(path_to_files)
for f in files:
if 'Excel' in f:
created_folder = os.path.join(path_to_files, 'Excel')
filepath = os.path.join(path_to_files, f)
os.makedirs(created_folder, exist_ok=True)
shutil.move(filepath, created_folder)
NB: You can add more if statements for different keywords like Excel
Use pathlib mkdir for creating the folders. Prepare the folders/keywords you want sort in the list 'folders'. And then what is important is skipping the folders because os.listdir() gives you the folders aswell (and there is an error if you want to move a folder into itself)
import os
import shutil
import pathlib
folders = ["vba", "Excel"]
path = "/home/vojta/Desktop/THESIS/"
for f in os.listdir():
if not os.path.isdir(os.path.join(path, f)): # skip folders
for fol in folders:
if fol in f:
pathlib.Path(os.path.join(path, fol)).mkdir(parents=True, exist_ok=True)
fol_path = os.path.join(path, fol)
shutil.move(os.path.join(path, f), os.path.join(fol_path, f))

How can I check if a file exists in python? [duplicate]

This question already has answers here:
How do I check whether a file exists without exceptions?
(40 answers)
Closed 3 years ago.
I am trying to make a python script to make entries in an excel file that will have daily entries.
I want to check if a file exists then open it.
if the file does not exist then I want to make a new file.
if have used os path exists to see if the file is present
workbook_status = os.path.exists("/log/"+workbookname+".xlxs")
if workbook_status = "True":
# i want to open the file
Else:
#i want to create a new file
I think you just need that
try:
f = open('myfile.xlxs')
f.close()
except FileNotFoundError:
print('File does not exist')
If you want to check with if-else than go for this:
from pathlib import Path
my_file = Path("/path/to/file")
if my_file.is_file():
# file exists
import os
import os.path
PATH='./file.txt'
if os.path.isfile(PATH) and os.access(PATH, os.R_OK):
print "File exists and is readable/there"
else:
f = open('myfile.txt')
f.close()
You should use following statement:
if os.path.isfile("/{file}.{ext}".format(file=workbookname, ext=xlxs)):
# Open file

How do i list folder in directory [duplicate]

This question already has answers here:
how to get all folder only in a given path in python?
(6 answers)
Closed 4 years ago.
This is my code :
import os
def get_file():
files = os.listdir('F:/Python/PAMC')
print(files)
for file in files:
print(file)
get_file()
How do i list only folders in a directory in python?
Tried and tested the below code in Python 3.6
import os
filenames= os.listdir (".") # get all files' and folders' names in the current directory
result = []
for filename in filenames: # loop through all the files and folders
if os.path.isdir(os.path.join(os.path.abspath("."), filename)): # check whether the current object is a folder or not
result.append(filename)
result.sort()
print(result)
#To save Foldes names to a file.
f= open('list.txt','w')
for index,filename in enumerate(result):
f.write("%s. %s \n"%(index,filename))
f.close()
Alternative way:
import os
for root, dirs, files in os.walk(r'F:/Python/PAMC'):
print(root)
print(dirs)
print(files)
Alternative way
import os
next(os.walk('F:/Python/PAMC'))[1]
Try a generator with os.walk to get all folders in the specified directory:
next(os.walk('F:/Python/PAMC'))[1]
If you want the folder names using a for loop, you can use the following code.
#--------*---------*---------*---------*---------*---------*---------*---------*
# Desc: Using 'yield' to get folder names in a directory
#--------*---------*---------*---------*---------*---------*---------*---------*
import os
import sys
def find_folders():
for item in os.listdir():
if os.path.isfile(item):
continue
else:
# # yield folder name
yield item
#--------*---------*---------*---------*---------*---------*---------*---------#
while 1:# M A I N L I N E #
#--------*---------*---------*---------*---------*---------*---------*---------#
# # set directory
os.chdir("C:\\Users\\Mike\\Desktop")
for folder in find_folders():
print (folder)
sys.exit() # END SAMPLE CODE SNIPPET

get script directory name - Python [duplicate]

This question already has answers here:
How do you properly determine the current script directory?
(16 answers)
Closed 2 years ago.
I know I can use this to get the full file path
os.path.dirname(os.path.realpath(__file__))
But I want just the name of the folder, my scrip is in. SO if I have my_script.py and it is located at
/home/user/test/my_script.py
I want to return "test" How could I do this?
Thanks
import os
os.path.basename(os.path.dirname(os.path.realpath(__file__)))
Broken down:
currentFile = __file__ # May be 'my_script', or './my_script' or
# '/home/user/test/my_script.py' depending on exactly how
# the script was run/loaded.
realPath = os.path.realpath(currentFile) # /home/user/test/my_script.py
dirPath = os.path.dirname(realPath) # /home/user/test
dirName = os.path.basename(dirPath) # test
>>> import os
>>> os.getcwd()
Just write
import os
import os.path
print( os.path.basename(os.getcwd()) )
Hope this helps...

how to check if a file is a directory or regular file in python? [duplicate]

This question already has answers here:
How to identify whether a file is normal file or directory
(7 answers)
Closed 3 years ago.
How do you check if a path is a directory or file in python?
os.path.isfile("bob.txt") # Does bob.txt exist? Is it a file, or a directory?
os.path.isdir("bob")
use os.path.isdir(path)
more info here http://docs.python.org/library/os.path.html
Many of the Python directory functions are in the os.path module.
import os
os.path.isdir(d)
An educational example from the stat documentation:
import os, sys
from stat import *
def walktree(top, callback):
'''recursively descend the directory tree rooted at top,
calling the callback function for each regular file'''
for f in os.listdir(top):
pathname = os.path.join(top, f)
mode = os.stat(pathname)[ST_MODE]
if S_ISDIR(mode):
# It's a directory, recurse into it
walktree(pathname, callback)
elif S_ISREG(mode):
# It's a file, call the callback function
callback(pathname)
else:
# Unknown file type, print a message
print 'Skipping %s' % pathname
def visitfile(file):
print 'visiting', file
if __name__ == '__main__':
walktree(sys.argv[1], visitfile)

Categories