I have Python script which reads files names from oldFiles.txt, iterate through files names which are files in a Linux directory, then update the files names using string.replace and finally run a subprocess to find those files (let's say in home directory to make the explanation and demo easier) and change their names using
subprocess.run(['mv', 'oldfile', 'newfile')]
Let's suppose I have files names with string "jane" and I want to replace it with "jdoe", a file's name example would be: abcd_jane.csv
The sys.argv is the argument which will be passed like the follow
I am using those empty files for local training, their names are saved in oldFiles.txt
sdafsdfs_jane.doc 12fgdf-jane.csv files_jane.txt each file's name is saved in one line.
Iterating and updating files names in oldFiles.txt is ok but I still couldn't figure out how to run the subprocess to achieve my goal like described above. This is what I came in, thank you very much. Sorry for my bad explanation.
mv: cannot stat '/home/user/sdafsdfs_jane.doc 12fgdf-jane.csv files_jane.tx': No such file or directory From the output I can understand that maybe the path is getting attached only to the first newName and not to the rest of files names or it could be bash is reading all files names as one file name but I still don't know how to solve it.
PS: I am not showing my username and I am replacing it with
user. So please change it into your current username.
PS: I am forced to use sys and subprocess modules, and also forced to apply all the mentioned details, its a homework assessment.
Thank you very much for your support and your comprehension.
#!/usr/bin/env python3 import sys import subprocess with open(sys.argv) as f: for name in f.readlines(): newName = name.strip() lastName = newName.replace("jane", "jdoe") subprocess.run(["mv", "/home/user/"+newName, "/home/user/"+lastName])
I modified the script to return list so I can flawlessly iterate through items, actually the script is successfully applied on the first file name only while still 2 others, any idea please? Thank you very much.
#!/usr/bin/env python3 import sys import subprocess with open(sys.argv, 'r') as f: content1 = f.readlines() content2 = [x.strip() for x in content1] content3 = [item.replace("jane", "jdoe") for item in content2] for x in content2: for i in content3: subprocess.run(['mv', '/home/ninja-coder/'+x, '/home/ninja-coder/'+i])