Python 3x - Remove numbers from file names - python

import os
def rename_files():
# (1) get file names from a folder
file_list = os.listdir(r"C:\Users\USEER\Desktop\Udacity\Udacity - Programming Foundation with Python\Project\prank\prank")
# print(file_list)
saved_path = os.getcwd()
print("Current Working Directory is " + saved_path)
os.chdir(r"C:\Users\USEER\Desktop\Udacity\Udacity - Programming Foundation with Python\Project\prank\prank")
# (2) for each file, rename file name
for file_name in file_list:
print("Old Name - " + file_name)
print("New Name - " + file_name.translate("0123456789"))
os.rename(file_name, file_name.translate("0123456789"))
os.chdir(saved_path)
rename_files()
The code above doesn't rename the file by removing the integers. Can anyone help? (Python 3x)

import re
new_name = re.sub('[0-9]', '', file_name)

In Python 3 the String.translate is gone. Therefore you need to use the str.translate. It needs 'str.maketrans' which normally creates a translation table with the first two arguments supplied(not needed in this example), the third argument supplies the characters to be stripped.
This line should have the desired effect ...
os.rename(file_name, file_name.translate(str.maketrans('','','0123456789'))
Previous suggestions used .strip() however in this case as the numbers are mixed in with the filenames (not before or after) I believe it would not work, another used Regular Expressions which is perfectly valid, however within the context of this particular Udacity course translate was the suggested solution.
Here are the docs for maketrans :
[https://docs.python.org/3/library/stdtypes.html#str.maketrans][1]

The problem is in your translate function that doesn't do anything. There are better options available, but if your want to use translate then the proper syntax is:
#!/usr/bin/env python2
import string
new_name = string.translate(file_name, None, "0123456789")

Here is one way of renaming files.
Use os.renames to rename the files
Use file_name.strip("0123456789") to remove numbers
Code is given below:
import os
def file_rename():
name_list=os.listdir(r"C:\python\prank")
print(name_list)
saved_path=os.getcwd()
print("Current working directory is"+saved_path)
os.chdir(r"C:\python\prank")
for file_name in name_list:
print("old name"+file_name)
print("new name"+file_name.strip("0123456789"))
os.renames(file_name,file_name.strip("0123456789"))
os.chdir(saved_path)
file_rename()
To read more about os.renames check here.
To read more about the strip function, check here.

Another way to do this without import re. Instead of utilizing the .translate, use the .strip.
os.rename(file_name, file_name.strip('0123456789'))
Another observation is that your code wont read the new file name after changing it. At the top of your code you are reading file names and saving those name in file_list
# (1) get file names from a folder
file_list = os.listdir(r"C:\Users\USEER\Desktop\Udacity\Udacity - Programming Foundation with Python\Project\prank\prank")
In the for loop, where you are changing the name of each file, YOU ARE NOT reading the new file's name. You need to do something like this.
# (2) for each file, rename file name
for file_name in file_list:
print("Old Name - " + file_name)
os.rename(file_name, file_name.strip("0123456789"))
# (3) read file's name again... 'file_list' has old names
new_file_list = os.listdir(r"C:\Users\USEER\Desktop\Udacity\Udacity - Programming Foundation with Python\Project\prank\prank")
for file_name in new_file_list:
print("New file's name: " + new_file_name)
os.chdir(saved_path)

import os
def rename_files():
#1 Get file names from the folder
file = os.listdir(r"C:\Web\Python\prank")
print(file)
saved_path = os.getcwd()
print("Current Working Directory is"+saved_path)
os.chdir(r"C:\Web\Python\prank")
#2 For each file name rename file names
for file_name in file:
print("Old Name - " + file_name)
os.rename(file_name,file_name.strip("0123456789"))
print("New Name - " + file_name)
os.chdir(saved_path)
rename_files()

enter code here
import os
dir="/home/lucidvis/myPythonHome/prank/"
def rename_files():
# get file names from a folder
filenames = os.listdir(dir)
# print(filenames)
for file in filenames:
#print(file)
try:
#with os.open(filename for filename in filenames,"r+"):
#read_file = filename.read()
# new_name = file.translate(str.maketrans('','', "0123456789"))
new_filname = (file.translate(str.maketrans('','', "0123456789"))).replace(" ","")
#print(dir+new_file_name)
os.rename(dir+file,dir+new_file_name)
except SyntaxError as e:
print(e)
continue
# for each file, rename filename
rename_files()
import os
dir="/home/lucidvis/myPythonHome/prank/"
def rename_files():
# get file names from a folder
filenames = os.listdir(dir)
# iterate through the list of filenames
for file in filenames:
#print(file)
try:
#assign a variable to new names for easy manipulation
new_filname = (file.translate(str.maketrans('','', "0123456789"))).replace(" ","")
#concatenating the directory name to old and new file names
os.rename(dir+file,dir+new_file_name)
#just to manage errors
except SyntaxError as e:
print(e)
continue
#file renaming function call
rename_files()

will guys i was trying to solve this problem because i see udacity online courses and it require to rename file without numbers thanks to simon for his replay i have to figured it out
this is my code to rename files without numbers, hope it jhelp anyone who stuck
import os
import re
def rename():
#get the list of the photo name
plist = os.listdir(r"D:\pay\prank")
print(plist)
#removing the numbers from the photo names
os.chdir(r"D:\pay\prank")
for pname in plist :
os.rename(pname, re.sub('[0-9]', '' , pname))
print(pname)
rename()

import os
import re
from string import digits
#Get file names
file_list = os.listdir(r"C:\Users\703305981\Downloads\prank\prank")
print(file_list)
#chenage directory.
os.chdir(r"C:\Users\703305981\Downloads\prank\prank")
print (os.getcwd())
#Change the Name.
for file_name in file_list:
os.rename(file_name, re.sub(r'[0-9]+', '', file_name))

Related

How to keep the zipped file's name after extracting it?

I have a zip file named model_A.zip, which is renamed from model_B.zip . The original folder, which is to zip model_B.zip, is model_B. I use zipfile to extract it.
import zipfile
with zipfile.ZipFile('model_A.zip', "r") as zip_ref:
zip_ref.extractall(path_to_unzip)
After extracting it, the folder's name becomes model_B/. However, what I want is model_A/. I can use functions like shutil.move(model_B, model_A), but the problem is I don't know the folder name after extracting (if model_A.zip is renamed from model_C.zip, the folder name is model_C).
Is there a way to get model_A without extra operations?
What I gather from your question is that there is a single top file/directory in your zip file. After or during extraction, you wish to rename that file/directory. If getting the name of this top file is your objective, then maybe the following code can help. You can rename this file/directory after the extraction is complete.
import zipfile
import os
path_to_unzip ="D:\\Codes"
zip_file_loc = 'D:\\Codes\\Solo\\File_Sorter2.zip'
rename = "model"
with zipfile.ZipFile(zip_file_loc, "r") as zip_ref:
topdir = zip_ref.namelist()[0]
if(topdir[-1] == '/'):
topdir = topdir[:-1]
zip_ref.extractall(path_to_unzip)
sp = topdir.split('.')
if len(sp)>1:
rename = "model" + "." + sp[len(sp) - 1]
oldname = os.path.join(path_to_unzip, topdir)
newname = os.path.join(path_to_unzip, rename)
print(newname)
try:
os.rename(oldname, newname)
except:
print("Check if file already exists")

CHange multiple file name python

I am having trouble with changing file name manually
I have folder with lots of file with name like
202012_34324_3643.txt
202012_89543_0292.txt
202012_01920_1922.txt
202012_23442_0928.txt
202012_21346_0202.txt
what i want it to be renamed as below removing numbers before _ and after _ leaving number in between underscore.
34324.txt
89543.txt
01920.txt
23442.txt
21346.txt
i want a script that reads all files in the folder renames it like above mentioned.
Thanks
You could try using the os library in python.
import os
# retrieve current files in the directory
fnames = os.listdir()
# split the string by '_' and access the middle index
new_names = [fnames.split('_')[1]+'.txt' for fname in fnames]
for oldname, newname in zip(fnames, new_names):
os.rename(oldname, newname)
This will do the work for the current directory.
import os
fnames = os.listdir()
for oldName in fnames:
if oldName[-4:] == '.txt' and len(oldName) - len(oldName.replace("_","")) == 2:
s = oldName.split('_')
os.rename(oldName, s[1]+'_'+s[2]+'.txt')

Need help creating a txt file in a folder which, is in the same directory

I'm pretty new to python. I have a homwork problem where we need to analyze corpora and then compare them. We also have to save the files as a .txt file after is has been processed with an attribute, the size.
So I need to create a .txt file in a seperate folder called trigram-models.
This folder is in the same directory as my python file. I think i have to use the os module but i'm not sure how.
Here is my code:
from langdetect import read_trigrams, trigram_table, write_trigrams
import os
def make_profiles(datafolder, profilefolder, size):
filelist = []
for file in os.listdir('./training'):
filelist.append(file)
print(filelist)
for file in filelist:
filen = "./training/"+file
print("fi", filen)
maketable = trigram_table(filen, size)
readdata = read_trigrams(filen)
#print("re", readdata)
splitname = str(file).split('-')
newname = splitname[0] + "." + str(size) + '.txt'
endtable = write_trigrams(readdata, newname)
return (endtable)
make_profiles("./training", "./trigram-models", 20)
To create a directory, I would use the following format which relies on a try / catch and prevents an error if the directory already exists:
dirName = 'tempDir'
try:
# Create target Directory
os.mkdir(dirName)
print("Directory " , dirName , " Created ")
except FileExistsError:
print("Directory " , dirName , " already exists")
To change your directory you can use the following:
os.chdir(directoryLocation)
I recommend reading chapter 8 in automating the boring stuff with python.
I hope this helps. If you have any questions please don't hesitate to ask.
First of all, be sure to indent all the code in your method for it to be appropriately enclosed.
You are also passing relative paths (datafolder, profilefolder) for your folders as method arguments, so you should use them inside the method instead.
Lastly, to create a file in a folder, I would recommend using the following algorithm:
file_path = '/'.join(profilefolder, newname)
with open(file_path, 'w') as ouf:
ouf.write(endtable)
You will probably need to replace "endtable" with a string representation of your data.
Hope it helps.
As to clarify on toti08's answer, you should replace os.absdir with os.path.absdir.
filelist = [os.path.abspath(f) for f in os.listdir(data_folder)]
instead of
filelist = [os.abspath(f) for f in os.listdir(data_folder)]
Your function is not using the argument profileFolder, where you specify the name of the output directory. So first of all you should use this information for creating a folder before processing your files.
So first thing would be to create this output directory.
Second is to save your files there, and to do that you need to append the file name to the output directory. Something like this:
def make_profiles(data_folder, output_folder, size):
filelist = []
for file in os.listdir(data_folder):
filelist.append(file)
# Create output folder
if not os.path.exists(output_folder):
os.mkdir(output_folder)
for file in filelist:
filen = "./training/"+file
#print("fi", filen)
splitname = str(file).split('-')
# Create new file by appending name to output_folder
newname = os.path.join(output_folder, splitname[0] + "." + str(size) + '.txt')
return (endtable)
make_profiles(./training, './trigram-models', 20)
Note that you can also specify the relative folder name (i.e. "trigram-models" only) and then create the output directory by appending this name to the current path:
output_folder = os.path.join(os.getcwd(), output_folder)
Also (not related to the question) this piece of code could be optimized:
filelist = []
for file in os.listdir(data_folder):
filelist.append(file)
os.listdir already returns a list, so you could directly write:
filelist = os.listdir(data_folder)
But since you're interested in the absolute path of each file you could better do:
filelist = [os.path.abspath(f) for f in os.listdir(data_folder)]
where you basically take each file returned by os.listdir and you append its absolute path to your file list. Doing this you could avoid the line filen = "./training/"+file.
So in the end your code should look something like this:
def make_profiles(data_folder, output_folder, size):
filelist = [os.abspath(f) for f in os.listdir(data_folder)]
# Create output folder
if not os.path.exists(output_folder):
os.mkdir(output_folder)
for file in filelist:
splitname = str(file).split('-')
# [...add other pieces of code]
# Create new file by appending name to output_folder
newname = os.path.join(output_folder, splitname[0] + "." + str(size) + '.txt')
# [...add other pieces of code]
return (endtable)
make_profiles(./training, './trigram-models', 20)

How to rename the file extension, by removing archive dates

I am thinking this code should take all my files within the folder, and rename .pdf_(date) to .pdf. However, it is not.
import os,sys
folder = 'C:\/MattCole\/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('.pdf*', '.pdf')
output = os.rename(infilename, newname)
Example: file1.pdf_20160614-050421 renamed to file.pdf
There would be multiple files in the directory. Can someone tell me what I am doing wrong? I have also tried counting the extension and used '.pdf????????????', '.pdf'
This is a bit silly, you've got some perfectly good code here that you're not using. You should use it.
import os,sys
folder = 'C:\/MattCole\/test'
for filename in os.listdir(folder):
infilename = os.path.join(folder,filename)
if os.path.isfile(infilename):
oldbase, oldext = os.path.splitext(infilename)
if oldext.startswith('.pdf'):
output = os.rename(infilename, oldbase+'.pdf')
You want to split the old file name on _, then take the first part as new name:
>>> old_name = 'file1.pdf_20160614-050421'
>>> new_name = old_name.split('_')[0]
>>> new_name
'file1.pdf'

Beginner Python : How to save output in the same location and with a different name?

I would like to save the output in the same location as the input but using a different, but still related, name.
Minimal Example:
This script searches for lines containing the string "NFS" in the input file. Then, it prints the results to another file.
I would like to save the print result to an output file in the same location as the input file but using a different name like "inputfilename.out.csv".
Here is the code :
from __future__ import print_function
import sys
fname = sys.argv[1]
out = open(fname.out.csv, "w") #this doesn't work but this is the idea
with open(fname) as file:
reader = file.readlines()
for line in reader:
if "NFS" in line:
print(line, file = out)
Any suggestions ?
You could use os.path.splitext() to extract extension:
import os
name, ext = os.path.splitext(fname)
output_filename = name + ".out" + ext
Or if you want to change the name completely, you could use os.path.dirname() to get the parent directory:
import os
dirpath = os.path.dirname(fname)
output_filename = os.path.join(dirpath, "outputfile.txt")
Use concatenation to add ".out.csv" to the end of your string.
out = open(fname + ".out.csv", "w")
If the input filename is "inputfilename", then the output will be "inputfilename.out.csv". This may be undesirable behavior if the input filename already has an extension. Then "inputfilename.csv" will become "inputfilename.csv.out.csv". In which case, you may wish to use os.path to construct the new name.
import os.path
filename = "inputfilename.csv"
root, extension = os.path.splitext(filename)
output_filename = root + ".out" + extension
print output_filename
Result:
inputfilename.out.csv

Categories

Resources