Python - Delete xlsx files from a folder - python

I am trying to delete all xlsx files from a folder, note it has files of other extension. Given below is what I have tried:
path = '/users/user/folder'. <-- Folder that has all the files
list_ = []
for file_ in path:
fileList = glob.glob(path + "/*.xlsx")
fileList1 = " ".join(str(x) for x in fileList)
try:
os.remove(fileList1)
except Exception as e:
print(e)
But the above does not delete the xlsx files.

Try:
import os
import glob
path = '/users/user/folder'
for f in glob.iglob(path+'/**/*.xlsx', recursive=True):
os.remove(f)

you can use this code to delete the xlsx or xls file
import os
path = r'your path '
os.chdir(path)
for file in os.listdir(path):
if file.endswith('.xlsx') or file.endswith('.xls'):
print(file)
os.remove(file)

You can use the below code as well to remove multiple .xlsx files in a folder.
import glob, os
path =r"folder path"
filenames = glob.glob(path + "/*.xlsx")
for i in filenames:
os.remove(i)

It would be better to use os.listdir() and fnmatch.
Try the below code .
`import os, fnmatch
listOfFiles = os.listdir('/users/user/folder') #filepath
pattern = "*.xslx"
for entry in listOfFiles:
if fnmatch.fnmatch(entry, pattern):
print ("deleting"+entry)
os.remove(entry)`

Related

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 :)

drilling down into dirs\sub-dirs looking for specific file names

drilling down into sub-dirs looking for specific files to modify.
Using glob.glob() to search all sub-dirs for files.
path = 'C:\Test\*\*[1234,349,4568]*.*'
#print(path)
files = glob.glob(path)
print(files)
for name in files:
with open(name,'r') as inputfile:
newText = inputfile.read().replace('5484522-102','P/N 545616-102')
print(newText)
with open(name, "w") as outputfile:
outputfile.write(newText)
print('Done !')
modifies the files called out in the path and many more I don't want to be modified. How do i modify only the files called out in the path?
#!/usr/bin/env python3
#This code finds the specific files listed in a dir and copies them to another dir.
There the files are read and the p/n replace with another p/n
import os
import shutil
import glob
import pandas as pd
#fill in the file name into this set
df = pd.read_csv('c:\Test\ReadFiles.csv')
path = 'C:\Test\Test\*.*'
dest_dir = 'C:\Test\Test' # New dir for the files found
src_dir = 'C:\Test' # Search dir
walking through the dir and files looking for the files in the set().
for (dirpath, dirnames, filenames) in os.walk(src_dir):
for fname in filenames:
if fname[:6] in df:
print(fname)
shutil.copy(os.path.join(dirpath, fname), dest_dir)
iterate through files found and change the part number
files = glob.glob(path)
print(files)
for name in files:
with open(name,'r') as inputfile:
newText = inputfile.read().replace('222222-101','111111-101')
with open(name, "w") as outputfile:
outputfile.write(newText)
print(outputfile)
print('Done !')

Zip Multiple files with multiple result in Python

Good Day!.
I would like to ask how can you convert a list of ".xlsx(excel)" file from specific folder location to ".zip" files.
Example:
Path:= C:\My_Program\zip_files
Inside my zip_file folder i have multiple ".xlsx" files.
Test1.xlsx
Test2.xlsx
Test3.xlsx
and i want the output to be in same folder but zip individually.
Output:
Test1.zip
Test2.zip
Test3.zip
Hope somebady can help me i am new to python2 or python3.
You have standard module zipfile to create ZIP, and glob.glob() or os.listdir() or os.walk() to get filenames in folder.
EDIT: should works (I works for me on Linux)
import os
import zipfile
folder = 'C:\\My_Program\\zip_files'
for filename in os.listdir(folder):
if filename.endswith('.xlsx'):
name_without_extension = filename[:-5] # string `.xlsx` has 5 chars
xlsx_path = os.path.join(folder, filename)
zip_path = os.path.join(folder, name_without_extension + '.zip')
zip_file = zipfile.ZipFile(zip_path, 'w')
# use `filename` (without folder name) as name inside archive
# and it will not create folders inside archive
zip_file.write(xlsx_path, filename)
zip_file.close()
EDIT: the same with glob
import os
import glob
import zipfile
folder = 'C:\\My_Program\\zip_files'
for file_path in glob.glob(folder+'\\*.xlsx'):
filename = os.path.basename(file_path)
print(filename)
name_without_extension = filename[:-5]
print(name_without_extension)
xlsx_path = os.path.join(folder, filename)
zip_path = os.path.join(folder, name_without_extension + '.zip')
zip_file = zipfile.ZipFile(zip_path, 'w')
# use `filename` (without folder name) as name inside archive
# and it will not create folders inside archive
zip_file.write(xlsx_path, filename)
zip_file.close()

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.

Change the file extension for files in a folder?

I would like to change the extension of the files in specific folder. i read about this topic in the forum. using does ideas, I have written following code and I expect that it would work but it does not. I would be thankful for any guidance to find my mistake.
import os,sys
folder = 'E:/.../1936342-G/test'
for filename in os.listdir(folder):
infilename = os.path.join(folder,filename)
if not os.path.isfile(infilename): continue
oldbase = os.path.splitext(filename)
infile= open(infilename, 'r')
newname = infilename.replace('.grf', '.las')
output = os.rename(infilename, newname)
outfile = open(output,'w')
The open on the source file is unnecessary, since os.rename only needs the source and destination paths to get the job done. Moreover, os.rename always returns None, so it doesn't make sense to call open on its return value.
import os
import sys
folder = 'E:/.../1936342-G/test'
for filename in os.listdir(folder):
infilename = os.path.join(folder,filename)
if not os.path.isfile(infilename): continue
oldbase = os.path.splitext(filename)
newname = infilename.replace('.grf', '.las')
output = os.rename(infilename, newname)
I simply removed the two open. Check if this works for you.
You don't need to open the files to rename them, os.rename only needs their paths. Also consider using the glob module:
import glob, os
for filename in glob.iglob(os.path.join(folder, '*.grf')):
os.rename(filename, filename[:-4] + '.las')
Something like this will rename all files in the executing directory that end in .txt to .text
import os, sys
for filename in os.listdir(os.path.dirname(os.path.abspath(__file__))):
base_file, ext = os.path.splitext(filename)
if ext == ".txt":
os.rename(filename, base_file + ".text")
import os
dir =("C:\\Users\\jmathpal\\Desktop\\Jupyter\\Arista")
for i in os.listdir(dir):
files = os.path.join(dir,i)
split= os.path.splitext(files)
if split[1]=='.txt':
os.rename(files,split[0]+'.csv')
#!/usr/bin/env python
'''
Batch renames file's extension in a given directory
'''
import os
import sys
from os.path import join
from os.path import splitext
def main():
try:
work_dir, old_ext, new_ext = sys.argv[1:]
except ValueError:
sys.exit("Usage: {} directory old-ext new-ext".format(__file__))
for filename in os.listdir(work_dir):
if old_ext == splitext(filename)[1]:
newfile = filename.replace(old_ext, new_ext)
os.rename(join(work_dir, filename), join(work_dir, newfile))
if __name__ == '__main__':
main()
If you have python 3.4 or later, you can use pathlib. It is as follows. This example is for changing .txt to .md.
from pathlib import Path
path = Path('./dir')
for f in path.iterdir():
if f.is_file() and f.suffix in ['.txt']:
f.rename(f.with_suffix('.md'))
With print and validation.
import os
from os import walk
mypath = r"C:\Users\you\Desktop\test"
suffix = ".png"
replace_suffix = ".jpg"
filenames = next(walk(mypath), (None, None, []))[2]
for filename in filenames:
if suffix in filename:
print(filename)
rep = input('Press y to valid rename : ')
if rep == "y":
for filename in filenames:
if suffix in filename:
os.rename(mypath+"\\"+filename, mypath+"\\"+filename.replace(suffix, replace_suffix))

Categories