0

I have ~60 subdirectories in a single directory. Each of these contain thousands of files, but they all contain a file named test_all_results.txt.

What I would like to do is to rename each test_all_results.txt file so that it now has the name:

foldername_all_results.txt

What is the best way to do this?

Workhorse
  • 1,500
  • 1
  • 17
  • 27
  • 5
    Did you attempt any code for this? – Devesh Kumar Singh Apr 30 '19 at 14:14
  • I am not super experienced in python, so I spent the last two hours trying to find an analogous answer with no result. – Workhorse Apr 30 '19 at 14:16
  • 1
    Please show an effort to solve this yourself, and we can help you with any specific issue you encounter. – glhr Apr 30 '19 at 14:16
  • 1
    Did you look at https://docs.python.org/3/library/os.html, this might have the functions you want! Try this out, and show us your work! And we can help on top of it – Devesh Kumar Singh Apr 30 '19 at 14:16
  • [How to go through directories](https://stackoverflow.com/a/2922878/10366273) and [how to rename a file](https://stackoverflow.com/a/2491232/10366273). – MyNameIsCaleb Apr 30 '19 at 14:17
  • Possible duplicate of [How to rename a file using Python](https://stackoverflow.com/questions/2491222/how-to-rename-a-file-using-python) – Nordle Apr 30 '19 at 14:27

4 Answers4

1

You can do:

(change your code accordingly)

import os

# current directory is the target
direct = "."
for path, dirs, files in os.walk(direct):
    for f in files:
        if os.path.splitext(f)[0] == "test_all_results.txt":
            os.rename(os.path.join(path, f), os.path.join(path, "foldername_all_results.txt"))
R4444
  • 2,016
  • 2
  • 19
  • 30
1

Easily accomplished using Python os interface.

Assuming you are currently in the main directory:

import os
#get a list of all sub directories
subdir = os.listdir()

for dir in subdir:       
    if os.path.isdir(dir): #check if directory          
        os.chdir(dir) #move to sub directory
        os.rename('test_all_results.txt', 'foldername_all_results.txt')            
        os.chdir('..') #return to main directory
danny bee
  • 840
  • 6
  • 19
1

Using python in Linux, make this:

import os
os.system("mv old_name.txt new_name.txt")

You can automatize with a loop, renaming all filenames.

Angelo Mendes
  • 905
  • 13
  • 24
1

There's an answer that tells you to use the os.system() method, if you do decide to call Linux commands from Python, I'd advise that you use the subprocess module instead.

Here's how you'd run the mv command with two arguments using subprocess.call:

import subprocess

subprocess.call(["mv", "filename.txt", "new-name.txt"])

INFO: here's an old (but relevant) article that explains why it's dangerous to use these methods.

Good luck.

Malekai
  • 4,765
  • 5
  • 25
  • 60