I'm trying to make a script that copies all the files other than the zipped files from a source folder to another destination folder and extract zipped files from the source folder to the destination, this is what i have come till this far:
import os
import zipfile
import shutil
myPath = "Source dir"
for root, dirs, files in os.walk(myPath):
for file in files:
if file.endswith('.zip'):
fh = open(file, 'rb')
z = zipfile.ZipFile(fh)
for name in z.namelist():
outpath = "destination dir"#Put the name of the destination folder
z.extract(name, outpath)
fh.close()
else:
fileList = os.listdir('source dir')
for f in fileList:
shutil.copy2(f, 'destination directory')
The code shows no error but there is no output too.
From Python Standard Library To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name) so you should write
fh = open(so.path.join(root,file))
to have the correct path.
Related
I am trying to identify all .kml in a specific directory and save them into a new directory. Is this possible? I'm able to print the file path but I would like to use Python to copy those files to a new directory.
Here is my code so far:
import os
# traverse whole directory
for root, dirs, files in os.walk(r'C:\Users\file_path_here'):
# select file name
for file in files:
# check the extension of files
if file.endswith('.kml'):
# print whole path of files
print(os.path.join(root, file))
Try this:
import os
# traverse whole directory
for root, dirs, files in os.walk(r'C:\Users\file_path_here'):
# select file name
for each_file in files:
# check the extension of files
if each_file.endswith('.kml'):
# print whole path of files
print(os.path.join(root, file))
kml_file = open(each_file, "r")
content = kml_file.read()
file.close()
with open('newfile.kml', 'w') as f:
f.write(content)
I have a folder that contains a group of files with different extension like .txt , .png , .pdf etc.
I want to organize the files and save them in different folders, for example, each file.txt in one folder and file.png in an another folder and file.pdf in an another folder etc.
import os
path = r'C:\Users\ibrahim\Desktop\test'
text_files = [f for f in os.listdir(path) if f.endswith('.txt')]
text_files
In this script how can I separately move files into different folders?
Something like this should work:
import os
import shutil
# Note we have to escape our backslashes here
path = "C:\\Users\\ibrahim\\Desktop\\test\\"
for f in os.listdir(path):
# Path to the original file
original_file_path = os.path.join(path, f)
# Only operate on files
if os.path.isfile(original_file_path):
# Get file name portion only
file_name = os.path.basename(original_file_path)
# Get the extension of the file and create a path for it
extension = f.split(".")[-1]
extension_path = os.path.join(path, extension)
# Create the path for files with the extension if it doesn't exist
if not os.path.exists(extension_path):
os.makedirs(extension_path)
# Copy the files into the new directory (copying is safer than moving, just so we can ensure it works as expected)
shutil.copyfile(original_file_path, os.path.join(extension_path, file_name))
Note that this will not be clever in anyway, .jpeg files will go into a different folder than .jpg files.
Try this,
import os
import shutil
txt_path = os.path.join(os.getcwd(), "text")
png_path = os.path.join(os.getcwd(), "png")
pdf_path = os.path.join(os.getcwd(), "pdf")
if not os.path.isdir(txt_path):
os.makedirs(txt_path)
print("text folder created")
if not os.path.isdir(png_path):
os.makedirs(png_path)
print("png folder created")
if not os.path.isdir(pdf_path):
os.makedirs(pdf_path)
print("pdf folder created")
#files = ['a.png' , 'b.pdf', 'c.txt']
files = [f for f in os.listdir(path)]
for file in files:
file_path = os.path.join(os.getcwd(), file)
if file_path.endswith('.txt')==True:
print('move file to text folder')
shutil.move(file_path, txt_path)
if file_path.endswith('.png')==True:
print('move file to png folder')
shutil.move(file_path, png_path)
if file_path.endswith('.pdf')==True:
print('move file to pdf folder')
shutil.move(file_path, pdf_path)
I am trying to find all the files with name ACC.txt in a given folder and its subfolder and then append them to create a new file i.e. output_file.txt. All the files are not in the working directory.
I have written the following code, but it is throwing a empty file.Please correct the code
import os
import shutil
BASE_DIRECTORY = r'E:\equity research\test_data'
with open('output_file.txt','wb') as wfd:
for dirpath, dirnames, filenames in os.walk(BASE_DIRECTORY):
for filename in filenames:
if filename == "ACC.txt":
fullPath = os.path.join(dirpath, filename)
with open(fullPath,'rb') as fd:
shutil.copyfileobj(fd, wfd)
I have folder that has subfolders each with many different files.
I'd like to copy all of the files (not subdirectories) into one folder
import os
import shutil
src = r'C:\TEMP\dir'
dest = r'C:\TEMP\new'
src_files = os.listdir(src)
for file_name in src_files:
full_file_name = os.path.join(src, file_name)
if (os.path.isfile(full_file_name)):
shutil.copy(full_file_name, dest)
when I run the code, there is no error but no files is copied either.
I do not know what is wrong with the code.
You can try this
import os
import shutil
src = r'C:\TEMP\dir'
dest = r'C:\TEMP\new'
for path, subdirs, files in os.walk(src):
for name in files:
filename = os.path.join(path, name)
shutil.copy2(filename, dest)
Im trying to create a zipfile with the content of a folder ( some dirs and files ) using the code belllow:
import zip,os
path = "c:\\tester\\folderToZip"
zip = zipfile.ZipFile("zippedFolder.zip", "w")
for root, dirs, files in os.walk(path):
for file in files:
zip.write(os.path.join(root, file))
zip.close()
But after the code runs, when i check the zip file, the zip file, instead having the content of the folder "folderToZip" ( ex: f1,f2,f2, a.txt,b.txt,c.txt ) it have the full path of the variable path.
So, the question is, how can i create a zipfile based on a folder content, but not his fullpath ?
write takes a second optional parameter arcname, which when specified will provide the name for the file stored. Use that to specify the name you want.
If you only want the filename:
import zip,os
path = "c:\\tester\\folderToZip"
zip = zipfile.ZipFile("zippedFolder.zip", "w")
for root, dirs, files in os.walk(path):
for file in files:
filename = os.path.join(root, file)
zip.write(filename, filename)
zip.close()