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.
Related
So I started python today and can't rly go through some chaos I encountered on the internet for this topic.
Many solutions a I try with os.walk and glob don't work - I of course assume that's because it's my first day and I just went through some basic function knowledge.
Anyway - I have for example a directory X:\P4V where I have my Perforce and I would like to go through this directory and print a list of all the files that have word 'GRAPH' in the string.
I know it's basic sh*t but it srsly makes my head hurt.
Thx in advance, cheers.
Yes, so.. first of all sry for not providing the code - my bad and second: I managed to finally do it just didn't understand the os.walk module correctly.
import os
path = "X:/P4V"
def search_for_file():
for root, dirs, files in os.walk(path):
for file in files:
if file.endswith("GRAPH.uasset"):
path_file = os.path.join(root, file)
print(path_file)
search_for_file()
I wasn't able to fully understand the usage of file in for file in files.
Anyway, will try to write better questions from now on :)
Hope you all are good. I'm facing this problem while importing images from a directory inside my project directory. I don't what's the problem. I did this while putting the images in the main directory. It's worked perfectly fine but I want to now import images from my folder images . Here is the screenshot. I hope you all can understand what i'm trying to do The only problem is in that "if items.endswith("images.jpg").
Try this :
for items in os.listdir('images'):
if items.endswith('.jpg'):
image = Image.open(f'images/{items}')
Explanation:
os.listdir returns the files inside the directory which doesn't include the full path. ie. images/images.jpg.
So when using PIL you should add the master path at the beginning.
I can see there are two main problems, the first one is that you are checking the file extension with endswith('images/.jpg'), this should be endswith('.jpg'), the second one is that you are using os.listdir, which returns a list with the file names in the folder and not the full path, that means that you are trying to load the image from im_name.jpg and not images/im_name.jpg.
The solution to both of these problems would be to use the glob package, which lets you search for all files matching an extension, and returns the full path for each file. For example:
import glob
print(glob.glob('images/*.jpg'))
should print:
images/image1.jpg
images/image2.jpg
...
And these are enough to load them using PIL.
Cheers everybody,
I need help with something in python 3.6 exactly. So i have structure of data like this:
|main directory
| |subdirectory's(plural)
| | |.wav files
I'm currently working from a directory where main directory is placed so I don't need to specify paths before that. So firstly I wanna iterate over my main directory and find all subdirectorys. Then in each of them I wanna find the .wav files, and when done with processing them I wanna go to next subdirectory and so on until all of them are opened, and all .wav files are processed. Exactly what I wanna do with those .wav files is input them in my program, process them so i can convert them to numpy arrays, and then I convert that numpy array into some other object (working with tensorflow to be exact, and wanna convert to TF object). I wrote about the whole process if anybody has any fast advices on doing that too so why not.
I tried doing it with for loops like:
for subdirectorys in open(data_path, "r"):
for files in subdirectorys:
#doing some processing stuff with the file
The problem is that it always raises error 13, Permission denied showing on that data_path I gave him but when I go to properties there it seems okay and all permissions are fine.
I tried some other ways like with os.open or i replaced for loop with:
with open(data_path, "r") as data:
and it always raises permission denied error.
os.walk works in some way but it's not what I need, and when i tried to modify it id didn't give errors but it also didnt do anything.
Just to say I'm not any pro programmer in python so I may be missing an obvious thing but ehh, I'm here to ask and learn. I also saw a lot of similiar questions but they mainly focus on .txt files and not specificaly in my case so I need to ask it here.
Anyway thanks for help in advance.
Edit: If you want an example for glob (more sane), here it is:
from pathlib import Path
# The pattern "**" means all subdirectories recursively,
# with "*.wav" meaning all files with any name ending in ".wav".
for file in Path(data_path).glob("**/*.wav"):
if not file.is_file(): # Skip directories
continue
with open(file, "w") as f:
# do stuff
For more info see Path.glob() on the documentation. Glob patterns are a useful thing to know.
Previous answer:
Try using either glob or os.walk(). Here is an example for os.walk().
from os import walk, path
# Recursively walk the directory data_path
for root, _, files in walk(data_path):
# files is a list of files in the current root, so iterate them
for file in files:
# Skip the file if it is not *.wav
if not file.endswith(".wav"):
continue
# os.path.join() will create the path for the file
file = path.join(root, files)
# Do what you need with the file
# You can also use block context to open the files like this
with open(file, "w") as f: # "w" means permission to write. If reading, use "r"
# Do stuff
Note that you may be confused about what open() does. It opens a file for reading, writing, and appending. Directories are not files, and therefore cannot be opened.
I suggest that you Google for documentation and do more reading about the functions used. The documentation will help more than I can.
Another good answer explaining in more detail can be seen here.
import glob
import os
main = '/main_wavs'
wavs = [w for w in glob.glob(os.path.join(main, '*/*.wav')) if os.path.isfile(w)]
In terms of permissions on a path A/B/C... A, B and C must all be accessible. For files that means read permission. For directories, it means read and execute permissions (listing contents).
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.
On my plone site I have hundreds of files (pdf, doc, ...) in filefield of archetypes objects. Something went wrong during importation and all the filenames are missing. The problem is that when somebody wants to open the file, since the extension is missing, the browser doesn't always propose to open it with a viewer.
The user has to save the file and add an extension to open it.
Can I write a python script to rename all files with an extension depending on the filetype?
Thank you.
http://plone.org/documentation/manual/plone-community-developer-documentation/content/rename
you've all you need here :)
The important part is this: parent.manage_renameObject(id, id + "-old")
you can loop over the subobjects doing:
for i in context.objectIds():
obj = context[i]
context.manage_renameObject(i, i + ".pdf")
context is the folder where you put this script, the folder where you've all your pdfs
The standard library function os.rename(src, dst) will do the trick. That's all you need if you know what the extension should be (e.g. all the files are .pdf). If you have a mixed bag of .doc, .pdf, .jpg, .xls files with no extensions, you'll need to examine the file contents to determine the proper extension using something like python-magic.
import os
for fn in os.listdir(path='.'):
os.rename(fn, fn + ".pdf")