What's the best way to copy and move files in python to a different directory, and overwrite those files in the destination if they already exist?
Take a look at shutil.copyfile
file1=open('insert directory here').readlines()
file2=open('insert directory here', 'w')
file2.write(file1)
If either of the directories have spaces in them do this:
directory='insert directory here'
directory=directory.rstrip()
Then use the variable directory as you would use the 'insert directory here'.
Related
I have been trying to figure out for a while how to check if there are .pkl files in a given directory. I checked the website and I could find ways to find if there are files in the directory and list them, but I just want to check if they are there.
In my directory are a total of 7 .pkl files, as soon as I create one, the others are created so to check if the seven of them exist, it will be enough to check if one exists. Therefore, I would like to check if there is any .pkl file.
This is working if I do:
os.path.exists('folder1/folder2/filename.pkl')
But I had to write one of my file names. I would like to do so without searching for a specific file. I also tried
os.path.exists('folder1/folder2/*.pkl'),
but it is not working neither as I don't have any file named *.pkl.
You can use the python module glob (https://docs.python.org/3/library/glob.html)
Specifically, glob.glob('folder1/folder2/*.pkl') will return a list of all .pkl files in folder2.
You can use :
for dir_path, dir_names, file_names in os.walk(search_dir):
# Go over all files and folders
for file_name in file_names:
if (file_name.endswith(".pkl")):
# do something like break after the first one you find
Note : This can be used if you want to search entire directory with sub directories also
In case you want to search only one directory , you can run the "for" on os.listdir(path)
I am looking to write a piece of python code that deletes all folders and their contents, but does not delete individual files.
For example here are some files and folders contained in a directory (Folder B) along with the script file that does the deleting. How do I delete folderA, folderB,folderC,etc, but leave the files? Thanks
/Folder B
file.docx
fileB.docx
fileC.docx
pythonDeleteScript.py
folderA/
folderB/
folderC/
folderD/
Use os.listdir() to get the contents of the directory, os.path.isdir(path) to see if it is a folder, and if it is, shutil.rmtree(path) to delete the folder and all its content.
I need to make a script that will iterate through all the directories inside a directory. It should go into each directory, get its name and save it to a variable and comes back out, and then loops.
for dir in os.walk(exDir):
path = dir
os.chdir(path)
source = #dir trimmed to anything after the last /
os.chdir("..")
loops
It needs to go into the directory to do other things not mentioned above. I've only just started Python and have been stuck on this problem for the last day or so.
For each iteration of your for loop, dir is a tuple of format (filepath, subdirectories, files). As such dir[0] will give you the filepath.
It sounds like you just want to os.chdir for each folder recursively in exDir in which case the following will work:
for dir in os.walk(exDir):
os.chdir(dir[0])
...
We just switched over our storage server to a new file system. The old file system allowed users to name folders with a period or space at the end. The new system considers this an illegal character. How can I write a python script to recursively loop through all directories and rename and folder that has a period or space at the end?
Use os.walk. Give it a root directory path and it will recursively iterate over it. Do something like
for root, dirs, files in os.walk('root path'):
for dir in dirs:
if dir.endswith(' ') or dir.endswith('.'):
os.rename(...)
EDIT:
We should actually rename the leaf directories first - here is the workaround:
alldirs = []
for root, dirs, files in os.walk('root path'):
for dir in dirs:
alldirs.append(os.path.join(root, dir))
# the following two lines make sure that leaf directories are renamed first
alldirs.sort()
alldirs.reverse()
for dir in alldirs:
if ...:
os.rename(...)
You can use os.listdir to list the folders and files on some path. This returns a list that you can iterate through. For each list entry, use os.path.join to combine the file/folder name with the parent path and then use os.path.isdir to check if it is a folder. If it is a folder then check the last character's validity and, if it is invalid, change the folder name using os.rename. Once the folder name has been corrected, you can repeat the whole process with that folder's full path as the base path. I would put the whole process into a recursive function.
Is it possible to write a folder and its contents to an existing ZipFile?
I've been messing around with this for a while and can only manage to write the folder structure to the archive, anything inside the folder isn't copied.
I don't want to point to a specific file, because the idea is that the folder contents can change and the program will just copy the whole folder into the archive no matter what is inside.
Currently I have,
myzipfile.write('A Folder\\Another Folder\\')
but I want the contents of 'Another Folder' to be copied as well not just the empty folder
Hopefully you understand what I mean.
Use os.walk:
import os
for dirpath,dirs,files in os.walk('A Folder/Another folder'):
for f in files:
fn = os.path.join(dirpath, f)
myzipfile.write(fn)