I am trying to rename all files in a folder based on the extension. I want all files to be in .txt format. Files in the folder can be of different extension but I am trying to have them all renamed to .txt.
I tried to do the below
allFiles = 'Path where the files are located'
for filename in glob.iglob(os.path.join(allFiles, '*.0000')):
os.rename(filename, filename[:-5] + '.txt')
The above throws an error:
TypeError: expected str, bytes or os.PathLike object, not list
import os
def renameFilesToTxt(input_dir):
for path, subdirs, files in os.walk(input_dir):
for name in files:
filePath = os.path.join(path, name)
target_filePath = ''.join(filePath.split('.')[:-1])+".txt"
os.rename(filePath, target_filePath)
I create a script that will change your folder's all file extensions and the script is tested in my local pc.
In your desire folder run this script
import os
from pathlib import Path
items = os.listdir(".")
newlist = []
for names in items:
if names.endswith(".0000"):
newlist.append(names)
for i in newlist:
print(i)
p = Path(i)
p.rename(p.with_suffix('.txt'))
[Note : THE SCRIPT IS TESTED AND ITS WORK]
Related
I have a specific path with folders and files. I want to filter out files with pdf, docx,jpg extensions.
Already, I have a script to list all files. So I got stuck. Anyone who could help me out to filter out those files.
The code is below.
import os
path = r'C:\Users\PacY\Documents'
FileList = []
extensions = ['.pdf', '.docx', '.jpg']
for FileList in os.listdir(path):
print("\nFiles: ", FileList)
listdir() gives file names as strings and string has function endswith() (ends with) which can get single string (ie. filename.endswith('.pdf')) or tuple of strings (ie. filename.endswith( ('.pdf', '.docx', '.jpg') ))
import os
path = r'C:\Users\PacY\Documents'
extensions = ('.pdf', '.docx', '.jpg') # has to be tuple instead of list
for filename in os.listdir(path):
if filename.endswith( extensions ):
print("filename:", filename)
To make sure you can also convert name to lower() to recognize also .PDF, .Pdf, etc.
if filename.lower().endswith( extensions ):
import os
path = r'C:\Users\PacY\Documents'
extensions = ('.pdf', '.docx', '.jpg') # has to be tuple instead of list
filtered_filenames = []
for filename in os.listdir(path):
if filename.lower().endswith( extensions ):
#print("filename:", filename)
filtered_filenames.append(filename)
#filtered_filenames.append( os.path.join(path, filename) ) # full path
print(filtered_filenames)
by the way:
it works also with extensions which have more dots - like .pdf.zip or popular on linux .tar.gz
I would use the split method. Here an example printing all the files in a folder that have one of those extensions.
import os
path = r'C:\Users\PacY\Documents'
FileList = []
extensions = ['pdf', 'docx', 'jpg']
FileList = os.listdir(path)
for file in FileList:
if file.split('.')[-1] in extensions:
print(file)
import os
from os import path
print(os.path.realpath)
extension = '.epub'
dir_path = os.path.dirname(os.path.realpath(__file__))
# Making list of files with .epub extension
files = []
for directory, subdir_list, file_list in os.walk(dir_path):
for name in file_list:
if list(name.split("."))[1] == extension.strip("."):
files.append(name)
Above code returns list of all the files with requested extension for the directory and all subdirectories.
i would write code in bit different way where you can use pathlib.
import pathlib
path = r'C:\Users\PacY\Documents'
extensions = ['pdf', 'docx', 'jpg']
list(pathlib.Path(path).glob(extensions))
I'm attempting to rename multiple files in a github repo directory on windows 10 pro
The file extensions are ".pgsql" (old) and ".sql" (rename to)
I'm using vscode (latest) and python 3.7 (latest)
I can do it, one folder at a time, but whenever I have tried any recursive directory code I've looked up on here I cant get it to work.
Currently working single directory only
#!/usr/bin/env python3
import os
import sys
folder = 'C:/Users/YOURPATHHERE'
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('.pgsql', '.sql')
output = os.rename(infilename, newname)
I'd like to have it recursively start in a directory and change only the file extensions specified to .sql in all sub directories as well on windows, for example
folder = 'C:/Users/username/github/POSTGRESQL-QUERY/'
You can use os.walk(),
import os
folder = 'C:/Users/YOURPATHHERE'
for root, dirs, files in os.walk(folder):
for filename in files:
infilename = os.path.join(root,filename)
newname = infilename.replace('.pgsql', '.sql')
output = os.rename(infilename, newname)
I am extracting .tar.gz files which inside there are folders (with files with many extensions). I want to move all the .txt files of the folders to another, but I don't know the folders' name.
.txt files location ---> my_path/extracted/?unknown_name_folder?/file.txt
I want to do ---> my_path/extracted/file.txt
My code:
os.mkdir('extracted')
t = tarfile.open('xxx.tar.gz', 'r')
for member in t.getmembers():
if ".txt" in member.name:
t.extract(member, 'extracted')
###
I would try extracting the tar file first (See here)
import tarfile
tar = tarfile.open("xxx.tar.gz")
tar.extractall()
tar.close()
and then use the os.walk() method (See here)
import os
for root, dirs, files in os.walk('.\\xxx\\'):
txt_files = [path for path in files if path[:-4] == '.txt']
OR use the glob package to gather the txt files as suggested by #alper in the comments below:
txt_files = glob.glob('./**/*.txt', recursive=True)
This is untested, but should get you pretty close
And obviously move them once you get the list of text files
new_path = ".\\extracted\\"
for path in txt_files:
name = path[path.rfind('\\'):]
os.rename(path, new_path + name)
I am trying the script below to rename all files in a folder.It is working fine,But when i am trying to run it outside the folder.It shows error.
import os
path=os.getcwd()
path=os.path.join(path,'it')
filenames = os.listdir(path)
i=0
for filename in filenames:
os.rename(filename, "%d.jpg"%i)
i=i+1
'it' is the name of the folder in which files lie.
Error:FileNotFoundError: [Errno 2] No such file or directory: '0.jpg' -> '0.jpg'
Print is showing names of files
When you do os.listdir(path) you get the filenames of files in the folder, but not the complete paths to those files. When you call os.rename you need the path to the file rather than just the filename.
You can join the filename to its parent folder's path using os.path.join.
E.g. os.path.join(path, file).
Something like this might work:
for filename in filenames:
old = os.path.join(path, filename)
new = os.path.join(path, "%d.jpg"%i)
os.rename(old, new)
i=i+1
You need to mention complete or relative path to file.
In this case, it should be
path + '/' + filename
or more generally,
newpath = os.path.join(path, filename)
I'm trying to scrape filenames inside a folder and then make directories for each filename inside another folder. This is what I've got so far but when I run it, it doesn't create the new folders in the destination folder. When I run it in the terminal it doesn't return any errors.
import os
import shutil
folder = "/home/ro/Downloads/uglybettyfanfiction.net/"
destination = "/home/ro/A Python Scripts/dest_test/"
# get each files path name
def ensure_dir(f):
d = os.path.dirname(f)
if not os.path.exists(d):
os.makedirs(d)
for files in os.listdir(folder):
new_path = folder + files
ensure_dir(new_path)
You've got a few mistakes. No need to use dirname and you should write to your destination, not the same folder:
def ensure_dir(f):
if not os.path.exists(f):
os.mkdir(f)
for files in os.listdir(folder):
new_path = destination + files
ensure_dir(new_path)