user3817675
user3817675

Reputation: 117

Python: rename files based on a Python list

I have a directory that contains a thousand or so txt files. I've read and explored these files with glob (searching for specific strings within the file) and I've appended the filenames of the files of interest to a list in Python, like so:

list_of_chosen_files = ['file2.txt', 'file10.txt', 'file17.txt', ...]

I'll be using this list for other things as well, but now I'm trying to figure out how to use the OS module to cross-reference the filenames in the directory against the list above and, if the filename is in that list, to add "1-" to the beginning of the filename. I've saved "1-" in a variable for reuse as well. Here's what I have so far: -

var = "1-"

import os
for filename in os.listdir("."):
    if filename == list_of_chosen_files[:]:
        os.rename(filename, var+filename)
        print filename

It's running without any errors in anaconda, but nothing's printing and none of the files are getting renamed. I feel like it should be such an easy fix, but I'm concerned about poking around directories with the OS module if I don't really know what I'm doing yet.

Any help would be greatly appreciated! Thanks!

Upvotes: 1

Views: 6896

Answers (2)

Ankur Anand
Ankur Anand

Reputation: 3904

Error : if filename == list_of_chosen_files[:]:

os.listdir(".")is only giving you back the basename results. Not full path. They don't exist in your current working directory. You would need to join them back with the root:

root = 'full Path of your directory'
for item in os.listdir(root):
    fullpath = os.path.join(root, item)
    os.rename(fullpath, fullpath.replace('filename', 'var+filename'))

Upvotes: 1

Matt Habel
Matt Habel

Reputation: 1543

Your issue is this line:

if filename == list_of_chosen_files[:]:

You're comparing a single string (filename) to an entire list (list_of_chosen_files[:] just gives you back the whole list). If you want to check if the filename is in the list, use this:

if filename in list_of_chosen_files:

This will check to see if list_of_chosen_files contains filename.

Upvotes: 3

Related Questions