Reputation: 31
this code moves all pdf files into a folder called pdf.It moves the first file then get error for moved file: [WinError 2] The system cannot find the file specified: 'C:\Users\farbod\Desktop\Print Form.pdf' -> 'C:/Users/farbod/Desktop/pdf/Print Form.pdf' note: I also used shutil instead of pathlib.Same error
import os
from pathlib import Path
path ="C:/Users/farbod/Desktop"
pdf_folder_path = "C:/Users/farbod/Desktop/pdf"
files=[]
os.chdir(path)
files = os.listdir(path)
for file in files:
file_path= path + '/' + file
file_name,file_ext= os.path.splitext(file_path)
if file_ext==".pdf":
os.rename(file_path,pdf_folder_path+'/'+file)
Path(file_path,).rename(pdf_folder_path+'/'+file)
else:
continue
Upvotes: 2
Views: 9723
Reputation: 1734
I think this is the code you are looking for
Tell me if there's any errors
import os
# from pathlib import Path
os.chdir("C:/Users/farbod/Desktop")
files = os.listdir()
for file in files:
if file.split('.')[-1] == "pdf":
os.rename(file, f"/pdf/{file}")
# Path(file).rename(f"/pdf/{file}")
# I can't understand why you have to move a file using 2 same functioning lines
# (or guess what, i don't know to use pathlib. os.rename is enough to move a file)
Upvotes: 0
Reputation: 31
fixed and working code.Thank you Mr. Ghost Ops
import os
pdf_folder_path = "/pdf/"
os.chdir("C:/Users/farbod/Desktop")
files = os.listdir()
for file in files:
file_path= f"{file}"
file_name,file_ext= os.path.splitext(file_path)
if file_ext==".pdf":
#your if statement didnt work because i had a folder called pdf.
os.rename(file_path,"C:/Users/farbod/Desktop/pdf"+"/"+file)
Upvotes: 1