How can I iterate over files in a given directory?

Python 3.6 version of the above answer, using os – assuming that you have the directory path as a str object in a variable called directory_in_str: import os directory = os.fsencode(directory_in_str) for file in os.listdir(directory): filename = os.fsdecode(file) if filename.endswith(“.asm”) or filename.endswith(“.py”): # print(os.path.join(directory, filename)) continue else: continue Or recursively, using pathlib: from pathlib import … Read more

Getting a list of all subdirectories in the current directory

Do you mean immediate subdirectories, or every directory right down the tree? Either way, you could use os.walk to do this: os.walk(directory) will yield a tuple for each subdirectory. Ths first entry in the 3-tuple is a directory name, so [x[0] for x in os.walk(directory)] should give you all of the subdirectories, recursively. Note that … Read more

If a folder does not exist, create it

As others have said, use System.IO.Directory.CreateDirectory. But, you don’t need to check if it exists first. From the documentation: Any and all directories specified in path are created, unless they already exist or unless some part of path is invalid. If the directory already exists, this method does not create a new directory, but it … Read more

How do I get the full path of the current file’s directory?

The special variable __file__ contains the path to the current file. From that we can get the directory using either pathlib or the os.path module. Python 3 For the directory of the script being run: import pathlib pathlib.Path(__file__).parent.resolve() For the current working directory: import pathlib pathlib.Path().resolve() Python 2 and 3 For the directory of the … Read more

How do I check if directory exists in Python?

Use os.path.isdir for directories only: >>> import os >>> os.path.isdir(‘new_folder’) True Use os.path.exists for both files and directories: >>> import os >>> os.path.exists(os.path.join(os.getcwd(), ‘new_folder’, ‘file.txt’)) False Alternatively, you can use pathlib: >>> from pathlib import Path >>> Path(‘new_folder’).is_dir() True >>> (Path.cwd() / ‘new_folder”https://stackoverflow.com/”file.txt’).exists() False

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)