python rename all files in subdirectories - python

i have two folder and each folder has six file with different extension (.txt, .jpg, .tiff etc) and i want to rename each file name with same name (don't want to change file extension) using Python.
could please help me out. I am new to programming and am starting to learn Python
Thanks in advance.

List all files in the directory using os.listdir, and then use os.rename
to rename all files, also use os.path.splitext to extract extension and file name
import os
folder_name = '<folder_where_we_have_files>'
name = '<name_for_file>'
for file in os.listdir(folder_name):
#Get the full file path
file_path = os.path.join(folder_name, file)
#Get the file name and it's extension
file_name, extension = os.path.splitext(file_path)
#We don't want to rename file which is already renamed
if name not in file_name:
#Create the full path of the new file
new_file = os.path.join(folder_name, name + extension)
#Rename the file to new file
os.rename(file_path, new_file)

Try this:-
for filename in os.listdir(folder_name):
src=foldername+filename
dst=new_name+filename.split(".")[1]
dst=folder_name+dst
os.rename(src,dst)

Related

How to alter file type and then save to a new directory?

I have been attempting to change all files in a folder of a certain type to another and then save them to another folder I have created.
In my example the files are being changed from '.dna' files to '.fasta' files. I have successfully completed this via this code:
files = Path(directory).glob('*.dna')
for file in files:
record = snapgene_file_to_seqrecord(file)
fasta = record.format("fasta")
print(fasta)
My issue is now with saving these files to a new folder. My attempt has been to use this:
save_path = Path('/Users/user/Documents...')
for file in files:
with open(file,'w') as a:
record = snapgene_file_to_seqrecord(a)
fasta = record.format("fasta").read()
with open(save_path, file).open('w') as f:
f.write(fasta)
No errors come up but it is definitely not working. I can see that there may be an issue with how I am writing this but I can't currently think of a better way to do it.
Thank you in advance!
Hi, You can use os lib to rename the file with the new extension (type)
import os
my_file = 'my_file.txt'
base = os.path.splitext(my_file)[0]
os.rename(my_file, base + '.bin')
And you can use shutil lib to move the file to a new directory.
import shutil
# absolute path
src_path = r"E:\pynative\reports\sales.txt"
dst_path = r"E:\pynative\account\sales.txt"
shutil.move(src_path, dst_path)
Hope that can be of help.

Keeping renamed text files in original folder

This is my current (from a Jupyter notebook) code for renaming some text files.
The issue is when I run the code, the renamed files are placed in my current working Jupyter folder. I would like the files to stay in the original folder
import glob
import os
path = 'C:\data_research\text_test\*.txt'
files = glob.glob(r'C:\data_research\text_test\*.txt')
for file in files:
os.rename(file, file[-27:])
You should only change the name and keep the path the same. Your filename will not always be longer than 27 so putting this into you code is not ideal. What you want is something that just separates the name from the path, no matter the name, no matter the path. Something like:
import os
import glob
path = 'C:\data_research\text_test\*.txt'
files = glob.glob(r'C:\data_research\text_test\*.txt')
for file in files:
old_name = os.path.basename(file) # now this is just the name of your file
# now you can do something with the name... here i'll just add new_ to it.
new_name = 'new_' + old_name # or do something else with it
new_file = os.path.join(os.path.dirname(file), new_name) # now we put the path and the name together again
os.rename(file, new_file) # and now we rename.
If you are using windows you might want to use the ntpath package instead.
file[-27:] takes the last 27 characters of the filename so unless all of your filenames are 27 characters long, it will fail. If it does succeed, you've stripped off the target directory name so the file is moved to your current directory. os.path has utilities to manage file names and you should use them:
import glob
import os
path = 'C:\data_research\text_test*.txt'
files = glob.glob(r'C:\data_research\text_test*.txt')
for file in files:
dirname, basename = os.path.split(file)
# I don't know how you want to rename so I made something up
newname = basename + '.bak'
os.rename(file, os.path.join(dirname, newname))

File writing is not working with pyPdf?

I am newer to python. I was try open the pdf files and write its content into the
new text files. That the text files name are generate by the pdf name. I tried so far but it is not give what i expect. How can i achieve it
import glob, os
import pyPdf
os.chdir("pdf/")
for file in glob.glob("*.pdf"):
filena = file
filename = "c:/documents/"+filena+".txt"
target = open(filename,'w')
pdf = pyPdf.PdfFileReader(open(filena,"rb"))
for page in pdf.pages:
target.write (page.extractText())
target.close()
Results the Error
File "c:/documents/atpkinase.pdf.txt",line 7, in <module>
target = open(filename,'w')
IOError: [Errno 2] No such file or directory: "c:/documents/atpkinase.pdf.txt"
Looks like if the directory "c:/documents/" does not exist. To write file to it you must create directory first. To check directory existent (and create it if needed) you can use
dir = "c:/documents"
if not os.path.exists(dir):
os.makedirs(dir)
Also, filea contains file name with extension, and when you create filename you need only a file name of old file without extension.

Reading/Writing to and from a file using the path

How do I go about reading from or writing to a file that isn't in the same folder as the file itself.
I'm trying to write a function that allows user input to find the file by using the path itself. I have to set it up where the user inputs the file name, then the path
I have to then concatenate them together to form the finished path to locate the file.
Use os.path.join() to construct file paths from distinct parts:
import os.path
dirname = '/foo/bar/baz'
filename = 'ham_n_spam'
path = os.path.join(dirname, filename)

os.rename() file to part of folder name

I have multiple folders that look like folder.0 and folder.1.
Inside each folder there is one file ('junk') that I want to copy and rename to the .0 or .1 part of the folder name in which it currently resides.
Here is what I'm trying to do:
inDirec = '/foobar'
outDirec = '/complete/foobar'
for root, dirs,files in os.walk(inDirec):
for file in files:
if file =='junk'
d = os.path.split(root)[1]
filename, iterator = os.path.splitext(d) # folder no. captured
os.rename(file, iterator+file) # change name to include folder no.
fullpath = os.path.join(root,file)
shutil.copy(fullpath,outDirec)
This returns:
os.rename(file,iterator+file)
OSError: [Errno 2] No such file or directory
I'm not even sure I should be using os.rename. I just want to pull out files == 'junk' and copy them to one directory but they all have the exact same name. So I really just need to rename them so they can exist in the same directory. Any help?
Update
for root, dirs,files in os.walk(inDirec):
for file in files:
if file =='junk'
d = os.path.split(root)[1]
filename, iterator = os.path.splitext(d) # folder no. captured
it = iterator[-1] # iterator began with a '.'
shutil.copy(os.path.join(root,file),os.path.join(outDirec,it+file))
Your problem is that your program is using the working directory at launch for your rename operation. You need to provide full relative or absolute paths as arguments to os.rename().
Replace:
os.rename(file, iterator+file)
fullpath = os.path.join(root,file)
shutil.copy(fullpath,outDirec)
With (if you want to move):
os.rename(os.path.join(root, file), os.path.join(outDirec, iterator+file))
Or with (if you want to copy):
shutil.copy(os.path.join(root, file), os.path.join(outDirec, iterator+file))
NOTE: The destination directory should already exist or you will need code to create it.

Categories

Resources