davids163
davids163

Reputation: 21

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:])

Upvotes: 0

Views: 474

Answers (2)

j-i-l
j-i-l

Reputation: 10957

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.

Upvotes: 1

tdelaney
tdelaney

Reputation: 77337

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))

Upvotes: 0

Related Questions