I'm trying to write a function which will allow me move .xlsm files between folders. I'm aware I can use shutil.move(), however, I'm trying to build a function that will take a file path as a parameter/argument and then perform the procedure.
Here's what I have:
def FileMove(source):
import os
import shutil
source = 'C:\\Users\\FolderB\\'
archive = 'C:\\Users\\FolderA\\'
UsedFiles = os.listdir(source)
for file in UsedFiles:
shutil.move(source+file, archive)
This doesn't do anything. Just wondering if anyone could point me in the right direction
Cheers
So just delete def FileMove(source): and it works fine.
Or you do something like that:
import os
import shutil
def FileMove(source):
archive = 'C:\\Users\\FolderA\\'
UsedFiles = os.listdir(source)
for file in UsedFiles:
shutil.move(source+file, archive)
source = 'C:\\Users\\FolderB\\'
FileMove(source)
Related
I have been attempting to change all files in a folder of a certain type to another and then save them to another folder I have created.
In my example the files are being changed from '.dna' files to '.fasta' files. I have successfully completed this via this code:
files = Path(directory).glob('*.dna')
for file in files:
record = snapgene_file_to_seqrecord(file)
fasta = record.format("fasta")
print(fasta)
My issue is now with saving these files to a new folder. My attempt has been to use this:
save_path = Path('/Users/user/Documents...')
for file in files:
with open(file,'w') as a:
record = snapgene_file_to_seqrecord(a)
fasta = record.format("fasta").read()
with open(save_path, file).open('w') as f:
f.write(fasta)
No errors come up but it is definitely not working. I can see that there may be an issue with how I am writing this but I can't currently think of a better way to do it.
Thank you in advance!
Hi, You can use os lib to rename the file with the new extension (type)
import os
my_file = 'my_file.txt'
base = os.path.splitext(my_file)[0]
os.rename(my_file, base + '.bin')
And you can use shutil lib to move the file to a new directory.
import shutil
# absolute path
src_path = r"E:\pynative\reports\sales.txt"
dst_path = r"E:\pynative\account\sales.txt"
shutil.move(src_path, dst_path)
Hope that can be of help.
file = open(r"C:\Users\MyUsername\Desktop\PythonCode\configure.txt")
Right now this is what im using. However if people download the program on their computer the file wont link because its a specific path. How would i be able to link the file if its in the same folder as the script.
You can use __file__. Technically not every module has this attribute, but if you're not loading your module from a file, loading a text file from the same folder becomes a moot point anyway.
from os.path import abspath, dirname, join
with open(join(dirname(abspath(__file__)), 'configure.txt')):
...
While this will do what you're asking for, it's not necessarily the best way to store configuration.
Use os module to get your current filepath.
import os
this_dir, this_filename = os.path.split(__file__)
myfile = os.path.join(this_dir, 'configure.txt')
file = open(myfile)
# import the OS library
import os
# create the absolute location with correct OS path separator to file
config_file = os.getcwd() + os.path.sep + "configure.txt"
# Open file
file = open(config_file)
This method will make sure the correct path separators are used.
I am trying to make a program to organize my downloads folder every time I download something, but if I use this code:
import shutil
shutil.move("/Users/plapl/downloads/.zip", "/Users/plapl/Desktop/Shortcuts/winrar files")
shutil.move("/Users/plapl/downloads/.png", "/Users/plapl/Desktop/Shortcuts/images")
It searches for a file name called .zip and .png, but I want it to search for all files that are that type. Can anyone tell me how to do that?
You want to iterate over the files in the directory. Here is an example from source
import shutil
import os
source = os.listdir("/Users/plapl/downloads/")
destination = "/Users/plapl/Desktop/Shortcuts/winrar files"
for files in source:
if files.endswith(".zip"):
shutil.move(files,destination)
I made something based off of that, but it says unresolved reference 'file'
import shutil
import os
source = os.listdir("/Users/plapl/Downloads/")
destination1 = "/Users/plapl/desktop/Shortcuts/images"
destination2 = "/Users/plapl/Shortcuts/winrar files"
destination3 = "/Users/plapl/torrents"
for files in source:
if file.endswith(".png"):
shutil.move(files, destination1)
if file.endswith(".zip"):
shutil.move(files, destination2)
if file.endswith(".torrent"):
shutil.move(files, destination3)
It is complaining for the variable name file which is not defined.
You should use files since that is your iterating variable name.
I have some files in the same directory which have the same extension(.html). Those files need to all be copied to another directory. I've looked up documentations on both shutil and os but couldn't find any proper answer...
I have some pseudo codes as below:
import os, shutil
copy file1, file2, file3 in C:\abc
to C:\def
If anyone knows how to solve this, pls let me know. Appreciated!!
Some time ago I created this script for sorting files in a folder. try it.
import glob
import os
#get list of file
orig = glob.glob("G:\\RECOVER\\*")
dest = "G:\\RECOVER_SORTED\\"
count = 0
#recursive function through all the nested folders
def smista(orig,dest):
for f in orig:
#split filename at the last point and take the extension
if f.rfind('.') == -1:
#in this case the file is a folder
smista(glob.glob(f+"\\*"),dest)
else:
#get extension
ext = f[f.rfind('.')+1:]
#if the folder does not exist create it
if not os.path.isdir(dest+ext):
os.makedirs(dest+ext)
global count
os.rename(f,dest+ext+"\\"+str(count)+"."+ext)
count = count+1
#if the destination path does not exist create it
if not os.path.isdir(dest):
os.makedirs(dest)
smista(orig,dest)
input("press close to exit")
[assuming python3, but should be similiar in 2.7]
you can use listdir from os and copy from shutil:
import os, shutil, os.path
for f in listdir("/path/to/source/dir"):
if os.path.splitext(f)[1] == "html":
shutil.copy(f, "/path/to/target/dir")
warning: this is scrapped together without testing. corrections welcome
edit (cause i can't comment):
#ryan9025 splitext is fromos.path, my bad.
I finally got an correct answer by myself with a combinations of all the replies.
So if I have a python script in (a) directory, all the source files in (b) directory, and the destination is in (c) directory.
Below is the correct code that should work, and it looks very neat as well.
import os
import shutil
import glob
src = r"C:/abc"
dest = r"C:/def"
os.chdir(src)
for files in glob.glob("*.html"):
shutil.copy(files, dest)
My script I run will be on my mac.
My root is '/Users/johnle/Desktop/'
The purpose of the code is to move a tons of files.
On my desktop will be tons of .pdf files. I want to move the pdf files to '/Users/johnle/Desktop/PDF'
So : '/Users/johnle/Desktop/file.pdf' - > '/Users/johnle/Desktop/PDF/'
This is my code in python :
def moveFile(root,number_of_files, to):
list_of_file = os.listdir(root)
list_of_file.sort()
for file in list_of_file:
name = root + str(file)
dest = to + str(file)
shutil.move( name, dest )
You can use glob and shutil modules. For example:
import glob
import shutil
for f in glob.glob('/Users/johnle/Desktop/*.pdf'):
shutil.copy(f, '/Users/johnle/Desktop/PDF')
(this code hasn't been tested).
Note: my code copies files. If you want to move them, then replace shutil.copy with shutil.move.
In case you have .pdf files with inconsistent casing on their extensions (e.g. .PDF, .pdf, .PdF, ...), you can use something like this:
import os
import shutil
SOURCE_DIR = '/Users/johnle/Desktop/'
DEST_DIR = '/Users/johnle/Desktop/PDF/'
for fname in os.listdir(SOURCE_DIR):
if fname.lower().endswith('.pdf'):
shutil.move(os.path.join(SOURCE_DIR, fname), DEST_DIR)
The os module has lots of fun toys like this for manipulating files and other OS related operations.
You can use the rename function within the os module, to move the file to a new location.
import os
os.mkdir(<path>) #creates a new folder at the specified path
os.rename(<original/current path>, <new path>)