Print contents of a folder - python

Here is my example.
Ex:
I have a folder that contains another 3 folders (FoldA, FoldB, and FoldC), a .txt file, and a .png file.
I have the following working code which works to print the contents a folder or directory.
import pathlib
rd = pathlib.Path("E:\\Location\\MainFolder")
for td in rd.iterdir():
print(td)
The output is:
E:\Location\MainFolder\FoldA
E:\Location\MainFolder\FoldB
E:\Location\MainFolder\FoldC
E:\Location\MainFolder\image.png
E:\Location\MainFolder\text.txt
Does anyone know a quick way to only print the folders and not any other file type (.txt, .bmp, .png, etc.)? I've tried using .is_dir but it still prints everything.
Thanks in advance!

probably you did if td.is_dir with is a function, so you need to execute it like this:
import pathlib
rd = pathlib.Path(".")
for td in rd.iterdir():
if td.is_dir():
print(td)
Kinda common problem with pathlib at beginning :)

Related

How can I print all files within a folder?

I want to print a file first, before printing everything within a folder. I know how to import the file just to look at it.
To be more specific I am trying to print the file to my printer which is connected through Wi-Fi.
What I am asking:
What code is needed to print (hard copy to printer) 1 file?
What code is needed to print all files within a folder (hard copies to printer)?
Have you tried this solution? It appears to be as easy as
import os
os.startfile("C:/Users/TestFile.txt", "print")
Since I'm not on a Windows system, I can't test it, but the internet seems to agree.
Once you know how to print one, printing many should not be any harder than iterating over the contents of the directory and filtering for files. For example, since you already have os imported, lets itearete over "C:/Users/data", assuming that's where you keep all your files to be printed:
base_dir = "C:/Users/data"
for file in os.listdir(base_dir):
file_name = os.path.join(base_dir, file)
if os.path.isfile(file):
os.startfile(file, "print")
You can also try using Pathlib, but for such a simple use case the advantages of it over os are not that big.

Moving file based on first few words in name

I want to move a file that I downloaded.
I have tried this.
shutil.move('/Users/dgoodwin/Downloads/metrics-lifetime-20190513.csv', '/Users/dgoodwin/OneDrive/metrics-lifetime.csv')
This works as long as the name doesn't change. I found after another download that there is the date at the end which changes everyday.
Here is the image of the files I am working with. Files
I would like to just use the first part of the name "metrics-lifetime" to search for in my downloads but I can't find out how grab partial paths.
Any help would be great. Thank you!
You can use use the glob module
import glob
files = glob.glob('*.xlsx')
for file in files:
shutil.move(file, destination_path)
I will proceed to use folder hierarchy loading.
This is a Japanese homepage, but it is written here.

Finding latest file in a folder using python

I've searched for an answer for this but the answers still gave me an error message and I wasn't allowed to ask there because I had to make a new question. So here it goes...
I need my python script to use the latest file in a folder.
I tried several things, currently the piece of code looks like this:
list_of_files = glob.glob('/my/path/*.csv')
latest_file = max(list_of_files, key=os.path.getmtime)
But the code fails with the following comment:
ValueError: max() arg is an empty sequence
Does anyone have an idea why?
It should be ok if the list is not empty, but it seems to be. So first check if the list isn't empty by printing it or something similar.
I tested this code and it worked fine:
import os
import glob
mypath = "C:/Users/<Your username>/Downloads/*.*"
print(min(glob.glob(mypath), key=os.path.getmtime))
print(max(glob.glob(mypath), key=os.path.getmtime))
glob.glob has a limitation of not matching the files that start with a .
So, if you want to match these files, this is what you should do - (assume a directory having .picture.png in it)
import glob
glob.glob('.p*') #assuming you're already in the directory
Also, it would be an ideal way to check the number of files present in the directory, before operating on them.

List all files inside a folder in a zip file in python

I have a zip file structure like - B.zip/org/note.txt
I want to directly list the files inside org folder without going to other folders in B.zip
I have written the following code but it is listing all the files and directories available inside the B.zip file
f = zipfile.ZipFile('D:\python\B.jar')
for name in f.namelist():
print '%s: %r' % (name, f.read(name))
You can filter the yields by startwith function.(Using Python 3)
import os
import zipfile
with zipfile.ZipFile('D:\python\B.jar') as z:
for filename in z.namelist():
if filename.startswith("org"):
print(filename)
How to list all files that are inside ZIP files of a certain folder
Everytime I came into this post making a similar question... But different at the same time. Cause of this, I think other users can have the same doubt. If you got to this post trying this....
import os
import zipfile
# Use your folder path
path = r'set_yoor_path'
for file in os.listdir(os.chdir(path)):
if file[-3:].upper() == 'ZIP':
for item in zipfile.ZipFile(file).namelist():
print(item)
If someone feels that this post has to be deleted, please let m know. Tks

open file in python without file's full name?

I am trying to execute f = open('filename') in python.
However, I dont know the full name of the file. All I know is that it starts with 's12' and ends with '.ka',I know the folder where it's located, and I know it is the only file in that folder that starts and ends with "s12" and ".ka". Is there a way to do this?
Glob is your friend:
from glob import glob
filename = glob('s12*.ka')[0]
Careful though, glob returns a list of all files matching this pattern so you might want to assert that you get the file you actually want somehow.

Categories