patternpythonMinor
Move files to specific directory, according to file extension
Viewed 0 times
directoryfileextensionmovefilesspecificaccording
Problem
I've written the following script
Questions/Issues are the following:
import shutil,os,glob
# setting up destination folders
PYDEST = "/home/ubuntu/python-scripts/python-test"
TEXTDEST = "/home/ubuntu/python-scripts/texte-test"
def move8files(pwd):
PWD = pwd + "*"
for files in glob.glob(PWD):
if files.endswith(".txt"):
print(files)
shutil.move(files,TEXTDEST)
elif files.endswith(".py"):
shutil.move(files,PYDEST)
move8files("/home/ubuntu/python-scripts/")Questions/Issues are the following:
- How can I make it simpler, especially by using the
os.listdirbut with having the pathname (listdirdoes not give pathname)?
- Would it be possible to include a part in my script, where instead of saying which folders are for python or text files, it will look syntaxically at specific folders containing words like
pythonortextein it?
- What can I improve in my script, for better performance?
Solution
I have no idea, how to make it simpler. I could only offer an alternative:
I think
#!/usr/bin/env python
import os
import shutil
fullpath = os.path.join
python_directory = "./py"
start_directory = "./mixed"
text_files = "./txt"
def main():
for dirname, dirnames, filenames in os.walk(start_directory):
for filename in filenames:
source = fullpath(dirname, filename)
if filename.endswith("py"):
shutil.move(source, fullpath(python_directory, filename))
elif filename.endswith("txt"):
shutil.move(source, fullpath(text_files, filename))
if __name__ == "__main__":
main()I think
os.walk()is what you are looking for.Code Snippets
#!/usr/bin/env python
import os
import shutil
fullpath = os.path.join
python_directory = "./py"
start_directory = "./mixed"
text_files = "./txt"
def main():
for dirname, dirnames, filenames in os.walk(start_directory):
for filename in filenames:
source = fullpath(dirname, filename)
if filename.endswith("py"):
shutil.move(source, fullpath(python_directory, filename))
elif filename.endswith("txt"):
shutil.move(source, fullpath(text_files, filename))
if __name__ == "__main__":
main()Context
StackExchange Code Review Q#138852, answer score: 4
Revisions (0)
No revisions yet.