Moving first file in folder to another folder - python

I am trying to move the first file in a folder into another folder using python. I am using shutil in order to do this.
I know that the following will move the whole S folder into the D folder. but how do I choose only the first file within the folder?
S = '/Users/kitchensink/Desktop/Sfolder'
D = '/Users/kitchensink/Desktop/Dfolder'
shutil.move(S, D)
print("moved")

You can use glob to find the files in a folder. For example if you want to have a list with all files in SFolder you can do this:
import glob
s_files = glob.glob('/Users/kitchensink/Desktop/Sfolder/*')
To get the first file, simply take the first element from s_files.
After this you can still use shutil to do the actual moving.

Related

How to access files in multiple sub-directories using glob

I have several files stored in a folder called Originals. Originals is stored in a folder called B_Substrate, B_Substrate is stored in a folder called Substrate_Training and Substrate_Training is stored in a folder called Jacob_Images.
I am trying to access the files in the folder Originals using glob but unable to access them.
Can anyone help me understand how to access files in multiple sub directories
This is my code but it doesn't work
import glob
file = '/content/drive/My Drive/Jacob_Images/Substrate_Training/B_Substrate/Originals/*.jpg'
for f in glob.glob(file):
print(f)
Instead of specifying .jpg within the path itself, specify it in glob() function. So, you can try this:
import glob
file = '/content/drive/My Drive/Jacob_Images/Substrate_Training/B_Substrate/Originals'
for f in glob.glob(file + "/*.jpg"):
print(f)
Or you can use this code below borrowing code from this post.
for i in glob.glob('/home/studio-lab-user/sagemaker-studiolab-notebooks/Misc/tsv/**/*.csv', recursive=True):
print(i)
Your code also works. I am certain the issue is with the path you are providing.
Using your way:
Using my way:

Move files one by one to newly created directories for each file with Python 3

What I have is an initial directory with a file inside D:\BBS\file.x and multiple .txt files in the work directory D:\
What I am trying to do is to copy the folder BBS with its content and incrementing it's name by number, then copy/move each existing .txt file to the newly created directory to make it \BBS1, \BBS2, ..., BBSn (depends on number of the txt).
Visual example of the Before and After:
Initial view of the \WorkFolder
Desired view of the \WorkFolder
Right now I have reached only creating of a new directory and moving txt in it but all at once, not as I would like to. Here's my code:
from pathlib import Path
from shutil import copy
import shutil
import os
wkDir = Path.cwd()
src = wkDir.joinpath('BBS')
count = 0
for content in src.iterdir():
addname = src.name.split('_')[0]
out_folder = wkDir.joinpath(f'!{addname}')
out_folder.mkdir(exist_ok=True)
out_path = out_folder.joinpath(content.name)
copy(content, out_path)
files = os.listdir(wkDir)
for f in files:
if f.endswith(".txt"):
shutil.move(f, out_folder)
I kindly request for assistance with incrementing and copying files one by one to the newly created directory for each as mentioned.
Not much skills with python in general. Python3 OS Windows
Thanks in advance
Now, I understand what you want to accomplish. I think you can do it quite easily by only iterating over the text files and for each one you copy the BBS folder. After that you move the file you are currently at. In order to get the folder_num, you may be able to just access the file name's characters at the particular indexes (e.g. f[4:6]) if the name is always of the pattern TextXX.txt. If the prefix "Text" may vary, it is more stable to use regular expressions like in the following sample.
Also, the function shutil.copytree copies a directory with its children.
import re
import shutil
from pathlib import Path
wkDir = Path.cwd()
src = wkDir.joinpath('BBS')
for f in os.listdir(wkDir):
if f.endswith(".txt"):
folder_num = re.findall(r"\d+", f)[0]
target = wkDir.joinpath(f"{src.name}{folder_num}")
# copy BBS
shutil.copytree(src, target)
# move .txt file
shutil.move(f, target)

Rename files within a folder - Python

How can I rename files inside a folder without knowing their original name? For example I have a file.jpg and without knowing what it's called I want to call it test.jpg, this with all the files inside a folder.
Try this:
import os
import glob
# Getting all files in a folder (including hidden files)
files = os.listdir(os.path.expanduser("~/Downloads"))
# Getting all .jpg files in a directory
jpeg_files = glob.glob(os.path.expanduser("~/Downloads/*.jpeg"))
print(jpeg_files)
os.rename(jpeg_files[0], os.path.expanduser("~/Downloads/test.jpeg"))
If you want to rename all of the .jpeg files, then replace the last line with:
for file in jpeg_files:
os.rename(file, os.path.expanduser("~/Downloads/test.jpeg"))
Right now I'm using os.expanduser() just so that it's easier for people to test

Python | Moving specific Files in User created Folder

I wrote a short script, where I want to moves all .CR2 (in the next step I want to choose between the first the first 2 or 6 files) Files to a Folder, which has been created before as raw_input.
import os
from os import path
import shutil
import itertools
proname = raw_input("Please Name the Productfolder: ")
path = "/Volumes/01_Produktfotos/_2020-01-JANUAR/"
os.mkdir(proname)
os.chdir(proname)
os.makedirs('_final')
os.makedirs('_images')
os.makedirs('_psd')
sourcepath = '/Volumes/01_Produktfotos/_2020-01-JANUAR/03.01/'
sourcefiles = os.listdir(sourcepath)
destinationpath = '/Volumes/01_Produktfotos/_2020-01-JANUAR/03.01/%proname/_images/'
for file in sourcefiles:
if file.endswith('.CR2'):
shutil.move(os.path.join(sourcepath,file), os.path.join(destinationpath,file))
At the moment, the script creates the user specific Folder (proname) and generates the subfolder _images, _final & _psd inside of it.
My Problem is that it doesn't moves the files from the top folder in the user created folder.
The Perfect Result would be if
I can choose a Productfolder Name
It creates inside of the Folder the subfolder _images, _final & _psd
I can choose if I want the first 2-6 .CR2 Files inside of the Subfolder _images of the created Productfolder
The Script is running till there are no .CR2 Files left
Any help or hints are welcome (:
Thx in advance
As in doc, dst is a directory, not a file.
shutil.move(src, dst) Recursively move a file or directory (src) to
another location (dst). If the destination is an existing directory, then src is moved inside that directory. If the destination already exists but is not a directory, it may be overwritten depending on os.rename() semantics.
# Before:
shutil.move(os.path.join(sourcepath,file), os.path.join(destinationpath,file))
# After:
shutil.move(os.path.join(sourcepath,file), destinationpath))
will work.
The following change solved the problem, with moving .CR2 Files in the specific proname Folder:
destinationpath = os.path.join('/Volumes/01_Produktfotos/_2020-01-JANUAR/03.01/', proname, '_images')
Now I'm in the next step, where not all .CR2 files should be moved. Just the first 2 or 6 files.

Import list of folder names in a folder with Python

So I've started down the path again of trying to automate something. My end game is to combine the data within Excel files containing the Clean Up in the file name and combine the data from a tab within these files named LOV. So basically it had to go into a folder with folders which have folders again that have 2 files, one file has the words Clean Up in the naming and is a .xlsx file. Which I need to only read those files and and pull the data from the tab called LOV into one large file. --- So that's my end goal. Which I just started and I am no where near, but now you know the end game.
Currently I'm stuck just getting a list of Folder names in the Master folder so I at least know it's getting there lol.
import os
import glob
import pandas as pd
# assigns directory location to PCC Folder
os.chdir('V:/PCC Clean Up Project 2017/_DCS Data SWAT Project/PCC Files
Complete Ready to Submit/Brake System Parts')
FolderList = glob.glob('')
print(FolderList)
Any help is appreciated, thanks guys!
EDITED
Firstly Its hard to understand your question. But from what I understand you need to iterate over folders and subfolders, you can do that with
for root, dirs, files in os.walk(source): #Give your path in source
for file in filenames:
if file.endswith((".xlxs")): # You can check for any file extension
filename = os.path.join(subdir,file)
dirname = subdir.split(os.path.sep)[-1] # gets the directory name
print(dirname)
If you only want the list of folders in your current directory, you can use os.path. Here is how it works:
import os
directory = "V:/PCC Clean Up Project 2017/_DCS Data SWAT Project/PCC Files
Complete Ready to Submit/Brake System Parts"
childDirectories = next(os.walk(directory))[1]
This will give you a list of all folders in your current directory.
Read more about os.walk here.
You can then go into one of the child directories by using os.chdir:
os.chdir(childDirectories[i])

Categories

Resources