So I made this script in to sort my desktop files into folders:
# Desktop Organization Script
import os
import shutil
userhome = os.path.expanduser('~')
src = userhome + '/Desktop/'
dst = src+ 'org/'
f_exe = [".exe",".lnk"]
f_web = [".php",".html",".css"]
f_images = [".jpg",".jpeg",".png",".ico",".gif",".JPG"]
f_video = [".avi"]
f_music = [".ogg",".wav",".mp3"]
f_document = [".txt",".pdf",".ppt",".pptx",".docx",".doc",".xls"]
f_multimedia = [".max",".m",".ase",".swf",".fla"]
f_zip = [".rar",".zip",".7z"]
f_book = [".epub"]
f_other = [".s2z",".url"]
formats = [f_exe,f_web,f_images,f_music,f_document,f_multimedia,f_zip,f_book,f_other,f_video]
def main():
txtlist = os.listdir(src);
for file in txtlist:
sortFiles(file)
def sortFiles(file):
for group in formats:
for format in group:
if file.endswith(format):
if format in f_exe: directory = "Executables"
if format in f_web: directory = "Web Development"
if format in f_images: directory = "Images"
if format in f_music: directory = "Music"
if format in f_document: directory = "Documents"
if format in f_multimedia: directory = "Multimedia"
if format in f_zip: directory = "RARs and ZIPs"
if format in f_book: directory = "Books"
if format in f_other: directory = "Others"
if format in f_video: directory = "Videos"
if not os.path.exists(dst+directory+"/"):
os.makedirs(dst+directory+"/")
shutil.move(src+file,dst+directory+"/")
main()
Although this does work with most files, sometimes there are files that won't be moved by this script, even if they share extension with files that did move properly. Actually, I am only having problems when moving shortcuts (.lnk extension). Some of them move, some of them do not move. The ones that don't move aren't even returned by the os.listdir() command. Any ideas?
As some *.lnk files are not listed by os.listdir(), I assume that they are not available in the user's desktop directory.
The reason for that might be that those files are stored in the "public desktop", i.e. c:\Users\Public\Desktop, and shared across all users.
Since you are only targeting the current user (userhome = os.path.expanduser('~')), the public Deskop remains "hidden" to your code.
Related
Looking for thoughts on how to read all csv files inside a folder in a project.
As an example, the following code is a part of my present working code, where my 'ProjectFolder' is on Desktop, and I am hardcoding the path. Inside the project folder, I have 'csvfolder' where I have all my csv files
However if I move the "ProjectFolder" to a different Hard drive, or other location, my path fails and I have to provide a new path. Is there an smart way to not worry about location of the project folder?
path = r'C:\Users\XXX\Desktop\ProjectFolder\csvFolder' # use your path
all_files = glob.glob(path + "/*.csv")
df_mm = pd.concat((pd.read_csv(f, usecols=["[mm]"]) for f in all_files),
axis = 1, ignore_index = True)
We have dynamic and absolute path concepts, just search on google "absolute vs relative path"; in your case if your python file is in the ProjectFolder you can simply try this:
from os import listdir
from os.path import dirname, realpath, join
def main():
# This is your project directory
current_directory_path = dirname(realpath(__file__))
# This is your csv directory
csv_files_directory_path = join(current_directory_path, "csvFolder")
for each_file_name in listdir(csv_files_directory_path):
if each_file_name.endswith(".csv"):
each_csv_file_full_path = join(csv_files_directory_path, each_file_name)
# Do whatever you want with each_csv_file_full_path
if __name__ == '__main__':
main()
I am doing a school assignment where I have to take input from a user and save it to a text file.
My file structure will be something like:
- Customer register
- Customer ID
- .txt files 1-5
It can be saved in the python folder and I can make the folders like this:
os.makedirs("Customer register/Customer ID")
My question is, how do I set the path the text files are to be stored in, in the directory when I don't know the directory? So that no matter where the program is run it is saved in the "Customer ID" folder I create (but on the computer the program is run on)?
Also, how do I make this work on both windows and mac?
I also want to program to be able to be executed several times, and check if the folder is there and save to the "Customer ID" folder if it already exists. Is there a way to do that?
EDIT:
This is the code I am trying to use:
try:
dirs = os.makedirs("Folder")
path = os.getcwd()
os.chdir(path + "/Folder")
print (os.getcwd())
except:
if os.path.exists:
path = os.getcwd()
unique_filename = str(uuid.uuid4())
customerpath = os.getcwd()
os.chdir(customerpath + "/Folder/" + unique_filename)
I am able to create a folder and change the directory (everything in "try" works as I want).
When this folder is created I want to create a second folder with a random generated folder name (used for saving customer files). I can't get this to work in the same way.
Error:
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'C:\Users\48736\PycharmProjects\tina/Folder/979b9026-b2f6-4526-a17a-3b53384f60c4'
EDIT 2:
try:
os.makedirs("Folder")
path = os.getcwd()
os.chdir(path + "/Folder")
print (os.getcwd())
except:
if os.path.exists:
path = os.getcwd()
os.chdir(os.path.join(path, 'Folder'))
print(os.getcwd())
def userId(folderid):
try:
if not os.path.exists(folderid):
os.makedirs(folderid)
except:
if os.path.exists(folderid):
os.chdir(path + "/Folder/" + folderid)
userId(str(uuid.uuid4()))
print(os.getcwd())
So I can now create a folder, change directory to the folder I have created and create a new folder with a unique filename within that folder.
But I can't change the directory again to the folder with the unique filename.
Any suggestions?
I have tried:
os.chdir(path + "/Folder/" + folderid)
os.chdir(path, 'Folder', folderid)
os.chdir(os.path.join(path, 'Folder', folderid))
But is still just stays in: C:\Users\47896\PycharmProjects\tina\Folder
You can use relative paths in your create directory command, i.e.
os.makedirs("./Customer register/Customer ID")
to create folder in project root (=where the primary caller is located) or
os.makedirs("../Customer register/Customer ID") in parent directory.
You can, of course, traverse the files tree as you need.
For specific options mentioned in your question, please, see makedirs documentation at Python 3 docs
here is solution
import os
import shutil
import uuid
path_on_system = os.getcwd() # directory where you want to save data
path = r'Folder' # your working directory
dir_path = os.path.join(path_on_system, path)
if not os.path.exists(dir_path):
os.makedirs(dir_path)
file_name = str(uuid.uuid4()) # file which you have created
if os.path.exists(file_name) and os.path.exists(dir_path):
shutil.move(file_name,os.path.join(dir_path,file_name))
else:
print(" {} does not exist".format(file_name))
I have a python script that creates a PDF and saves it in a subfoler of the folder where the script is saved. I have the following that saves the file to the subfolder:
outfilename = "Test" + ".pdf" #in real code there is a var that holds the name of the file
outfiledir = 'C:/Users/JohnDoe/Desktop/dev/PARENTFOLDER/SUBFOLDER/' #parent folder is where the script is - subfolder is where the PDFs get saved to
outfilepath = os.path.join(outfiledir, outfilename)
Is there a way I can save the PDFs to the subfolder without having to specify the full path? Lets say I wanted yto make this script an exe that multiple computers could use, how would I display the path so that the PDFs are just saved in the subfoler?
Thanks!
Try it:
import os
dir_name = os.path.dirname(os.path.abspath(__file__)) + '/subdir'
path = os.path.join(dir_name, 'filename')
I am looking for an simple file chooser dialog in sl4a. I have found a few native dialogs here but did not find the one I was looking for.
I wish I could save time by finding something readily available. A minimal code like filename = fileopendialog() would be a bonus.
Any ideas ?
I decided to write my own (see below for reference). This could probably be made better, any suggestions welcome.
import android, os, time
droid = android.Android()
# Specify root directory and make sure it exists.
base_dir = '/sdcard/sl4a/scripts/'
if not os.path.exists(base_dir): os.makedirs(base_dir)
def show_dir(path=base_dir):
"""Shows the contents of a directory in a list view."""
#The files and directories under "path"
nodes = os.listdir(path)
#Make a way to go up a level.
if path != base_dir:
nodes.insert(0, '..')
droid.dialogCreateAlert(os.path.basename(path).title())
droid.dialogSetItems(nodes)
droid.dialogShow()
#Get the selected file or directory .
result = droid.dialogGetResponse().result
droid.dialogDismiss()
if 'item' not in result:
return
target = nodes[result['item']]
target_path = os.path.join(path, target)
if target == '..': target_path = os.path.dirname(path)
#If a directory, show its contents .
if os.path.isdir(target_path):
show_dir(target_path)
#If an file display it.
else:
droid.dialogCreateAlert('Selected File','{}'.format(target_path))
droid.dialogSetPositiveButtonText('Ok')
droid.dialogShow()
droid.dialogGetResponse()
if __name__ == '__main__':
show_dir()
I have a folder path, for example /docs/word, and I would like to get the ID of the "word" folder (the last folder), in order to upload a file there. How do I get the ID?
So I figured it out. What you have to do is get the id of the root drive_service.about().get().execute()["rootFolderId"] , and then get the files in root, go to the next folder in the path, etc. btw, the function i wrote to list the folders inside a path and save them to a dictionary (using self.addPath())
def listFolders(self, path):
fId = self.getPathId(path) #get the id of the parent folder
files = self.drive_service.children().list(folderId=fId).execute() #Request children
files = files["items"] #All of the items in the folder
folders = []
for i in range(len(files)):
sId = files[i]["id"]
sFile = self.drive_service.files().get(fileId=sId).execute()
if sFile["labels"]["trashed"] == False and sFile["mimeType"] == "application/vnd.google-apps.folder":
self.addPath(path+sFile["title"]+"/", sFile["id"])
folders.append(sFile["title"])
return folders