How to change folder names in python?

2024/11/21 1:26:13

I have multiple folders each with the name of a person, with the first name(s) first and the surname last. I want to change the folder names so that the surname is first followed by a comma and then the first name(s) follow.

As an example, in the folder Test, i have:

C:/Test/John Smith
C:/Test/Fred Jones
C:/Test/Ben Jack Martin

and i want to make this:

C:/Test/Smith, John
C:/Test/Jones, Fred
C:/Test/Martin, Ben Jack

I tried some things with os.rename but i couldn't seem to make it work with the varying name length, and i wasn't sure how to insert the comma into the surname.

Also, some of the folder names are already in the correct form, so i need to skip these folders during the renaming. I think you can do this by just adding an if, so that if the folder name contains a comma it will continue.

Otherwise, the surname will always be the last word in the folder name.

Thanks for any help you can provide.

Answer

You can write it out fairly straight-forward, using os.listdir and the os.path functions:

import os
basedir = 'C:/Test'
for fn in os.listdir(basedir):if not os.path.isdir(os.path.join(basedir, fn)):continue # Not a directoryif ',' in fn:continue # Already in the correct formif ' ' not in fn:continue # Invalid formatfirstname,_,surname = fn.rpartition(' ')os.rename(os.path.join(basedir, fn),os.path.join(basedir, surname + ', ' + firstname))
https://en.xdnf.cn/q/26257.html

Related Q&A

Python return list from function

I have a function that parses a file into a list. Im trying to return that list so I can use it in other functions. def splitNet():network = []for line in open("/home/tom/Dropbox/CN/Python/CW2/net…

Python Json loads() returning string instead of dictionary?

Im trying to do some simple JSON parsing using Python 3s built in JSON module, and from reading a bunch of other questions on SO and googling, it seems this is supposed to be pretty straightforward. Ho…

Sort dataframe by string length

I want to sort by name length. There doesnt appear to be a key parameter for sort_values so Im not sure how to accomplish this. Here is a test df:import pandas as pd df = pd.DataFrame({name: [Steve, Al…

How to mock pythons datetime.now() in a class method for unit testing?

Im trying to write tests for a class that has methods like:import datetime import pytzclass MyClass:def get_now(self, timezone):return datetime.datetime.now(timezone)def do_many_things(self, tz_string=…

How can I select only one column using SQLAlchemy?

I want to select (and return) one field only from my database with a "where clause". The code is:from sqlalchemy.orm import load_only@application.route("/user", methods=[GET, POST])…

Get first list index containing sub-string?

For lists, the method list.index(x) returns the index in the list of the first item whose value is x. But if I want to look inside the list items, and not just at the whole items, how do I make the mos…

TypeError: Invalid dimensions for image data when plotting array with imshow()

For the following code# Numerical operation SN_map_final = (new_SN_map - mean_SN) / sigma_SN # Plot figure fig12 = plt.figure(12) fig_SN_final = plt.imshow(SN_map_final, interpolation=nearest) plt.col…

How to give delay between each requests in scrapy?

I dont want to crawl simultaneously and get blocked. I would like to send one request per second.

preprocess_input() method in keras

I am trying out sample keras code from the below keras documentation page, https://keras.io/applications/What preprocess_input(x) function of keras module does in the below code? Why do we have to do …

How to calculate precision and recall in Keras

I am building a multi-class classifier with Keras 2.02 (with Tensorflow backend),and I do not know how to calculate precision and recall in Keras. Please help me.