| | |
Rename files in Python
Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
![]() |
•
•
Join Date: Jun 2009
Posts: 8
Reputation:
Solved Threads: 0
Hi!
I'm about to rename a hole bunch of files in different folders and want to use Python to do it. The problem is that I want to keep parts of the file name from the old file and insert it into the new file in another location.
for example:
old file: abcXXabc
new file: XXdefghi
Where the XX is the part I want to keep; always numbers. XX is'nt always on the same location in the old file. Any suggestions on how to do this?
I'm a newb when it comes to Python but heard it was great to use for these types of problems and maybe i can become more skilld afterwards!
this is what I got so far..
directory = '.'
for file in os.listdir('directory'):
re.search('([0-9]+)', file).group(1)
if '&' in file :
os.rename(file, file.replace('abcabc', 'defghi'))
Greatly appreciate it! /MCl
I'm about to rename a hole bunch of files in different folders and want to use Python to do it. The problem is that I want to keep parts of the file name from the old file and insert it into the new file in another location.
for example:
old file: abcXXabc
new file: XXdefghi
Where the XX is the part I want to keep; always numbers. XX is'nt always on the same location in the old file. Any suggestions on how to do this?
I'm a newb when it comes to Python but heard it was great to use for these types of problems and maybe i can become more skilld afterwards!
this is what I got so far..
directory = '.'
for file in os.listdir('directory'):
re.search('([0-9]+)', file).group(1)
if '&' in file :
os.rename(file, file.replace('abcabc', 'defghi'))
Greatly appreciate it! /MCl
python Syntax (Toggle Plain Text)
>>> s="abc123abc" >>> t= "".join([x for x in s if x.isdigit()]+[x for x in s if not x.isdigit()]) >>> print t 123abcabc >>>
Try not to use regular expression. They are quite slow.
Last edited by siddhant3s; Jun 17th, 2009 at 10:33 am.
Siddhant Sanyam
(Not posting much)
Migrate to Standard C++ :When to tell your C++ Code is Non-Standard.
Please Read before posting: How To Ask Questions The Smart Way
(Not posting much)
Migrate to Standard C++ :When to tell your C++ Code is Non-Standard.
Please Read before posting: How To Ask Questions The Smart Way
•
•
Join Date: Jun 2009
Posts: 8
Reputation:
Solved Threads: 0
thanks! although, at another forum I i recieved this code (thanks E.T) but it doesnt handle file extensions.. does anyone got suggestions on how to solve that? (I got several file types that needs to be renamed..)
python Syntax (Toggle Plain Text)
import os import re pattern = re.compile(r"abc(\d+)abc") tree = os.walk("/path/to/ur/dir") targets = [] for dirpath, dirnames, names in tree: for name in names: m = pattern.match(name) if m: newname = os.path.join(dirpath, "%sdfghij" % m.group1)) os.rename(os.path.join(dirpath, name), newname)
Last edited by Tekmaven; Jun 18th, 2009 at 5:20 pm. Reason: Code Tags
If you just want to replace certain extensions, you can use something like this:
python Syntax (Toggle Plain Text)
file_list = [ 'list_nonunique1.py', 'Gene_read1.pyw', 'wx_psutil1.pyw', 'pa16names.txt', 'wxFrame_centerthings1.pyw', 'averagewords1.py', 'oneline.txt', 'tk_coinflip.pyw'] # replace extension .pyw with .py new_list= [] for fname in file_list: if '.pyw' in fname: fname = fname[:-3] + 'py' new_list.append(fname) print(fname) """ my result --> list_nonunique1.py Gene_read1.py wx_psutil1.py pa16names.txt wxFrame_centerthings1.py averagewords1.py oneline.txt tk_coinflip.py """
No one died when Clinton lied.
•
•
Join Date: Dec 2006
Posts: 1,024
Reputation:
Solved Threads: 288
A third option, if you want to keep the extension.
Python Syntax (Toggle Plain Text)
old_file_name = 'bc13abc2.txt' ## This assumes there is only one "." in the file name substrs = old_file_name.split(".") print substrs ## then use siddhant3s' example to find the digits, or some way ## using isdigit() and add substrs[1] (the ending) to that name. digits_list = [x for x in old_file_name if x.isdigit()] print digits_list ## which is the same as second_list = [] for x in old_file_name: if x.isdigit() second_list.append(x) ## you then have to .join into a string
Linux counter #99383
•
•
Join Date: Jun 2009
Posts: 8
Reputation:
Solved Threads: 0
Thank you woooee and Sneekula for all the help!
I still got some issues though. I dont want to specify the old file name since I got a great number of files with different file names and want to change the syntax on all of them. I was'nt very clear on what had to be done and aplgz for this..
for example:
old files:
1. abcde22ab.txt
2. abcde23ab.jpg
and also
3. fghij22fg.txt
4. fghij23fg.jpg
..and want the new files to look like this:
1. 22KLMNO.txt
2. 23KLMNO.jpg
and also
3. 22PQRST.txt
4. 23PQRST.jpg
That is, I want to keep the number in the file name and put in first in the new file name, I want to be able to specify which letters that should be in the new file (for fghik, replace with PQRST in another location of the string) and also to keep the extension of the original file. I would greatly appreciate any help and tips on how to solve this! /MCl
I still got some issues though. I dont want to specify the old file name since I got a great number of files with different file names and want to change the syntax on all of them. I was'nt very clear on what had to be done and aplgz for this..
for example:
old files:
1. abcde22ab.txt
2. abcde23ab.jpg
and also
3. fghij22fg.txt
4. fghij23fg.jpg
..and want the new files to look like this:
1. 22KLMNO.txt
2. 23KLMNO.jpg
and also
3. 22PQRST.txt
4. 23PQRST.jpg
That is, I want to keep the number in the file name and put in first in the new file name, I want to be able to specify which letters that should be in the new file (for fghik, replace with PQRST in another location of the string) and also to keep the extension of the original file. I would greatly appreciate any help and tips on how to solve this! /MCl
![]() |
Similar Threads
- Python query - rename a file name (Python)
- What are the .apy files in Python (Python)
- bulk rename files (IT Professionals' Lounge)
- Export multiple csv files with Python (Python)
- Executing DOS batch files in Python (Python)
- How to set default directory for saving files in Python IDLE (Python)
- Rename a Series of Files (Windows tips 'n' tweaks)
Other Threads in the Python Forum
- Previous Thread: Inheritance Problem?
- Next Thread: Python Help
| Thread Tools | Search this Thread |
alarm assignment avogadro beginner bluetooth character cmd code customdialog cx-freeze data decimals dictionary directory dynamic error examples exe file float format function generator getvalue gnu graphics gui halp homework http ideas import input ip itunes java leftmouse line linux list lists logging loop maintain maze millimeter module mouse number numbers output parsing path port prime programming projects push py2exe pygame pyglet pyqt python queue random recursion schedule screensaverloopinactive script scrolledtext slicenotation sqlite ssh stdout string strings sudokusolver table terminal text thread threading time tlapse tuple tutorial ubuntu unicode urllib urllib2 variable variables ventrilo verify vigenere web webservice wikipedia wxpython xlib






