Moving files with python using a list .txt - python

I want to move files from one directory to another from a .txt file containing the names of the files to be moved, the script must first browse the directory and if it finds the file it moves it to the new directory. Where to start? I've managed to do this for a file list but I'd like to do it directly via the .txt file without rewriting the names of the files to be moved
import shutil, os
files = ['file1.txt', 'file2.txt', 'file3.txt', 'file4.txt']
for file in files:
shutil.move(file, 'destination_directory')

As I know, U cant move your files with .txt
Just move your file_path
You can use my code below.
I have double checked and it work on my side.
Sorry for my poor English Skill :)
import os
import shutil
from pathlib import Path
def create_directory(dir_name: str):
"""To create directory before create files: txt, csv..."""
system_path = os.getcwd()
dir_path = os.path.join(system_path, dir_name)
try:
os.makedirs(dir_path, exist_ok=True)
except OSError as error:
print("Directory '%s' can not be created" % dir_name)
return dir_path
def create_files(dir_path: str, file_name: str):
"""Function for creating files"""
file_path = dir_path + fr"\{file_name}"
with open(file_path, "w") as open_file:
if Path(file_path).is_file():
print(f'File: {file_name} created successfully')
else:
print(f'File: {file_name} does not exist')
open_file.close() # Need to close.
return file_path
def main():
# Step 1: Creating file1.txt, file2.txt, file3.txt, file4.txt
file_one = create_files(create_directory("file1_dir"), 'file1.txt')
file_two = create_files(create_directory("file2_dir"), 'file2.txt')
file_three = create_files(create_directory("file3_dir"), 'file3.txt')
file_four = create_files(create_directory("file4_dir"), 'file4.txt')
# Step 2: Creating destination_directory:
destination_dir = create_directory('destination_directory')
files = [file_one, file_two, file_three, file_four]
# Step 3: Moving Your Files:
for file in files:
shutil.move(file, destination_dir)
if __name__ == "__main__":
main()

Related

open a folder to then use the files in python correctly

Usually I navigate to the folder I am extracting data from and copy the file name directly:
df2=pd.read_csv('10_90_bnOH-MEA.csv',usecols=[1])
If I have multiple files and want to do the same for all the files, how do I specify the folder to open and get all the files inside?
I want to run the above code without specifying the file's full path
(C:\Users\X\Desktop\Y\Z\10_90_bnOH-MEA.csv)
You want listdir from the os module.
import os
path = "C:\\Users\\X\\Desktop\\Y\\Z\\"
files = os.listdir(path)
print(files)
dataframe_list = []
for filename in files:
dataframe_list.append(pd.read_csv(os.path.join(path,filename)))
You should open the desired directory and loop through all the files then do something to them.
# import required module
import os
# assign directory
directory = 'files'
# iterate over files in
def goThroughDirectory(directory):
for filename in os.listdir(directory):
f = os.path.join(directory, filename)
# checking if it is a file
if os.path.isfile(f):
# do something
If you also want to loop through all the files in a directory you should add a check for if os.path.isdir(f) like this
...
def goThroughDirectory(directory):
for filename in os.listdir(directory):
f = os.path.join(directory, filename)
# checking if it is a file
if os.path.isfile(f):
# do something
elif os.path.isdir(f):
# its not a file but a directory then loop through that directory aswell
goThroughDirectory(directory + "\" + f)
for more information you should check geeksforgeeks

loop over files in sub zip-directories python

My txt.files are saved in zipped-subfolders as follows:
mainfolder.zip
mainfolder/folder1 (folder 1 is no zip-file)
mainfolder/folder1/subfolder11.zip
mainfolder/folder1/subfolder12.zip
mainfolder/folder2 (folder 2 is no zip file)
mainfolder/folder1/subfolder21.zip
mainfolder/folder1/subfolder22.zip
I want to loop over all the text files in subfolders of the mainfolder. Is there an easy way to do it?
I hope to help.
If the script is not in the folder with the folder to be searched, replace os.getcwd() with the path to the folder.
import os
import logging
from pathlib import Path
from shutil import unpack_archive
# unzipping all zipped folders
zip_files = Path(os.getcwd()).rglob("*.zip")
while True:
try:
path = next(zip_files)
except StopIteration:
break
except PermissionError:
logging.exception("permission error")
else:
extract_dir = path.with_name(path.stem)
unpack_archive(str(path), str(extract_dir), 'zip')
# finding and dealing with a .txt file
for root, dirs, files in os.walk(os.getcwd()):
for f in files:
if os.path.splitext(f)[1].lower() == ".txt":
with open(os.path.join(root, f)) as fi:
lines = fi.readlines()
print("File: ",os.path.join(root, f),"\ncontent: ", lines)
# all what you want do with file...
Nice day :)

Recursively rename file extensions

I am having a difficult time creating a python script that will rename file extensions in a folder and continue to do so in sub directories. Here is the script I have thus far; it can only rename files in the top directory:
#!/usr/bin/python
# Usage: python rename_file_extensions.py
import os
import sys
for filename in os.listdir ("C:\\Users\\username\\Desktop\\test\\"): # parse through file list in the folder "test"
if filename.find(".jpg") > 0: # if an .jpg is found
newfilename = filename.replace(".jpg","jpeg") # convert .jpg to jpeg
os.rename(filename, newfilename) # rename the file
import os
import sys
directory = os.path.dirname(os.path.realpath(sys.argv[0])) #get the directory of your script
for subdir, dirs, files in os.walk(directory):
for filename in files:
if filename.find('.jpg') > 0:
subdirectoryPath = os.path.relpath(subdir, directory) #get the path to your subdirectory
filePath = os.path.join(subdirectoryPath, filename) #get the path to your file
newFilePath = filePath.replace(".jpg",".jpeg") #create the new name
os.rename(filePath, newFilePath) #rename your file
I modified Jaron's answer with the path to the file and the complete example of renaming the file
I modified the answer of Hector Rodriguez Jr. a little bit because it would replace ANY occurance of ".jpg" in the path, e.g. /path/to/my.jpg.files/001.jpg would become /path/to/my.jpeg.files/001.jpeg, which is not what you wanted, right?
Although it is generally not a good idea to use dots "." in a folder name, it can happen...
import os
import sys
directory = os.path.dirname(os.path.realpath(sys.argv[0])) # directory of your script
for subdir, dirs, files in os.walk(directory):
for filename in files:
if filename.find('.jpg') > 0:
newFilename = filename.replace(".jpg", ".jpeg") # replace only in filename
subdirectoryPath = os.path.relpath(subdir, directory) # path to subdirectory
filePath = os.path.join(subdirectoryPath, filename) # path to file
newFilePath = os.path.join(subdirectoryPath, newFilename) # new path
os.rename(filePath, newFilePath) # rename
You can process the directory like this:
import os
def process_directory(root):
for item in os.listdir(root):
if os.path.isdir(item):
print("is directory", item)
process_directory(item)
else:
print(item)
#Do stuff
process_directory(os.getcwd())
Although, this isn't really necessary. Simply use os.walk which will iterate through all toplevel and further directories / files
Do it like this:
for subdir, dirs, files in os.walk(root):
for f in files:
if f.find('.jpg') > 0:
#The rest of your stuff
That should do exactly what you want.

For file in directories, rename file to directoryname

I have let's say 5 directories, let's call them dir1, dir2, dir3, dir4, dir5.
These are all in the current directory. Each of them contains 1 files called title.mkv. I want to rename the files to the directory name they are in, ie the file title.mkv in dir1, I want to rename to dir1.mkv.
I also want to then move the file to another folder. What python tools do I need for this besides os and glob?
If you have the full filename and directory, to rename the files, you can use
import os
f_name = 'E:/temp/nuke.mkv'
# Removes '/' at the end of string
while f_name.endswith('/'):
f_name = f_name[:-1]
# Generates List Containing Directories and File Name
f_name_split = f_name.split('/')
f_path = ''
# Iterates Through f_name_split, adding directories to new_f_path
for i in range(len(f_name_split)-1):
f_path += f_name_split[i] + '/'
# Makes New Name Based On Folder Name
new_name = f_name_split[-2] + '.mkv'
# Gets The Old File Name
f_name = f_name_split[-1]
# Renames The File
os.rename(f_path + f_name, f_path + new_name)
To go through all of the directories, you could do it recursively, have the system output it to a file [windows: dir /s /b /a > file.txt], or use os.walk. To move a file, you can use os.rename(source, destination)
The following should work, although you will have problems if there is more than one file per source folder:
import os
source_folder = r"c:\my_source_folder"
target_folder = r"c:\target_folder"
for directory_path, dirs, files in os.walk(source_folder):
# Current directory name
directory = os.path.split(directory_path)[1]
# Ensure only MKV files are processed
files = [file for file in files if os.path.splitext(file)[1].lower() == '.mkv']
# Rename each file
for file in files:
source = os.path.join(directory_path, file)
target = os.path.join(target_folder, directory + ".mkv")
try:
os.rename(source, target)
except OSError:
print "Failed to rename: {} to {}".format(source, target)
It will search all sub folders from the source folder and use the current folder name for the target name.
The following function uses shutil.move, which moves across filesystem and has overwrite protection in case destination file exists. File name can be relative.
from os.path import basename, dirname, isfile, abspath, splitext
from shutil import move
def rename_to_dirname_and_move(name, dst, overwrite=False, verbose=False):
"""renames 'name' to its directory name, keeping its extension
intact and moves to 'dst' directory across filesystem
"""
if not isfile(name):
raise ValueError("{} is not a file or doesn't exist".format(name))
abs_name = abspath(name)
dir_name = basename(dirname(abs_name))
new_name = '{}{}'.format(dir_name, splitext(name)[1])
dst_name = os.path.join(dst, new_name)
if not overwrite and isfile(dst_name):
raise OSError('file {} exists'.format(dst_name))
try:
move(abs_name, dst_name)
except Exception as e:
print("Can't move {} to {}, error: {}".format(abs_name, dst_name,e))
else:
if verbose:
print('Moved {} to {}'.format(abs_name, dst_name))

Zip Multiple Subdirectories With Path To Individual Zips

I need help editing the following script which Zips the contents of a directory. My end goal is creating a script that will look at C:\Test (which will have multiple directories inside) and make a new zip file with the contents of each directory in C:\Test. The tricky part is that I need the path to be C:\ even though the directories true paths are C:\Test. Is this possible or am I dreaming ?
Thanks
import zipfile, os
def makeArchive(fileList, archive):
try:
a = zipfile.ZipFile(archive, 'w', zipfile.ZIP_DEFLATED)
for f in fileList:
print "archiving file %s" % (f)
a.write(f)
a.close()
return True
except: return False
def dirEntries(dir_name, subdir, *args):
fileList = []
for file in os.listdir(dir_name):
dirfile = os.path.join(dir_name, file)
if os.path.isfile(dirfile):
if not args:
fileList.append(dirfile)
else:
if os.path.splitext(dirfile)[1][1:] in args:
fileList.append(dirfile)
# recursively access file names in subdirectories
elif os.path.isdir(dirfile) and subdir:
print "Accessing directory:", dirfile
fileList.extend(dirEntries(dirfile, subdir, *args))
return fileList
if __name__ == '__main__':
folder = r'C:\test'
zipname = r'C:\test\test.zip'
makeArchive(dirEntries(folder, True), zipname)
You can change the path of the file inside the archive as follows:
a.write(PATH_ON_FILESYSTEM,
DESIRED_PATH_IN_ARCHIVE
)

Categories