I've been tinkering with Python 3.66 a few days now on windows 7. Making good progress,
but I am totally stuck on how to make windows explorer open with my desired folder contents showing.
I have tried at least 7 different solutions from related questions on here but none seem to work. They all open explorer fine, but never with my Folder_selected
variable.
The explorer bit is the final line of code.
Here is the (badly coded I suspect) source:
#FRenum-v.04
#renumbers a folder of files to 01 onward preserving file extenders.
#Steve Shambles june 2018, my 2nd ever python program
from tkinter import filedialog
from tkinter import *
import os
import os.path
import subprocess
#user selects directory
root = Tk()
root.withdraw() #stop tk window opening
folder_selected = filedialog.askdirectory() #open file requestor
#change dir to folder selected by user,
os.chdir (folder_selected)
#path is now the dir
path=(folder_selected)
# read user selected dir
files = os.listdir(folder_selected)
# inc is counter to keep track of what file we are working on
inc = 1
for file in files:
#store file extender in string file_ext
file_ext = os.path.splitext(file)[1]
# build new filename, starting with a "0" then
#value of inc then add file extender
created_file=("0"+str(inc)+ file_ext)
#if file does not exist rename it
if not os.path.exists(created_file):
os.rename(file,created_file)
#next one please, until done
inc = inc+1 #add to counter
#open explorer showing folder of renamed files
subprocess.Popen(["C:\\Windows\\explorer.exe"])
#these do not work properly, opens in c: or my docs
#subprocess.Popen(["C:\\Windows\\explorer.exe"+ folder_selected])
#subprocess.Popen(["C:\\Windows\\explorer.exe", folder_selected])
#subprocess.Popen(["C:\\Windows\\explorer.exe","folder_selected"])
#todo
#---------
#ignore sub-folders
#confirm requestor
#undo feature
#find out how to stop dos box showing in compiles prg
so, your program is perfect, it's just that for some reason the wrong slashes were being used in the path, which python apparently could handle, but explorer.exe could not.
i ran your program, and printed out folder_selected and i got C:/Users/Michael/Desktop/test. which contains forward slashes, and windows paths use backslashes.
ao i would just replace subprocess.Popen(["C:\\Windows\\explorer.exe"]) to: subprocess.Popen(["C:\\Windows\\explorer.exe", folder_selected.replace('/', '\\')])
which will replace any forward slashes with backslashes, which explorer.exe should be able to handle.
hope this works :)
windows paths also cant have any kind of slash in them, so the user wont have a directory with any / in it, so replace should be fine
This problem caused by the difference between python/linux and windows representing paths.
I printed the folder_selected and get:
C:/Users/name/Documents/Zevel
You need to add the following right after calling askdirectory():
folder_selected = folder_selected.replace('/', '\\')
Making the path readable for windows, and now it looks like:
C:\Users\name\Documents\Zevel
Of course you need call subprocess.Popen(["explorer", folder_selected])
and every thing will work.
Related
first, I will describe in short the problem I want to solve:
I have a system UNIX based, that running an automatic run that causing images creation.
those images, are saving in a directory that creating during the run and the name of the directory is unpredictable [the name is depends in so many factors and not constant.]
that directory, is created under a constant path, which is:
/usr/local/insight/results/images/toolsDB/lauto_ptest_s + str(datetime.datetime.now()).split()[
0] + /w1
So, now I got a constant form of path which is a part of my full path.
I tried to get the full path in a stupid way:
I wrote a script that open a new terminal by pressing ctrl+alt+sft+w, writing in the terminal the cd command to the constant path, and pressing tab in order to complete the full path [In the constant path there is always one directory that created so pressing tab will always get me the full path].
Theoretically, I have a full path in a terminal, how can I copy this full path and make the function return it?
this is my code:
import pyautogui
import datetime
def open_images_directory():
pyautogui.hotkey('ctrl', 'alt', 'shift', 'w')
pyautogui.write(
'cd' + ' /usr/local/insight/results/images/toolsDB/lauto_ptest_s' + str(datetime.datetime.now()).split()[
0] + '/w1/')
pyautogui.sleep(0.5)
pyautogui.hotkey('tab') # now I have a full path in terminal which I want to return by func
open_images_directory()
Not sure how you use pyautogui for that, but the proper solution would be search the directory structure with some glob patterns
Example:
from pathlib import Path
const_path = Path("const_path")
for path in [p for p in const_path.rglob("*")]:
if path.is_dir():
print(f"found directory {path}")
else:
print(f"found your image {path}")
const_path.rglob("*") searches every path recursively, (so it will contain every subdirectory), the last one will be your path you are searching for.
I cannot figure out the best way to find a specific folder and send files to another specific folder, especially if the users directory is slightly different than what I have coded.
I'm working on a program that has a folder of content to grab from and the user basically picks items and when they're done, it creates a folder full of things including the images they chose. I've gotten it to work (and creating all necessary folders in the user's directory works fine but once it becomes more complex, it doesn't work some of the time) but I would like it to work every time, regardless of the user and where they've placed my program on their computer.
an example of relevant code I currently have which I'm sure is redundant compared to what I could be using instead:
init python:
import os
import shutil
current_dir = os.path.normpath(os.getcwd() + "../../")
def grab_content():
filetocopy = "image%s.png"%image_choice ##(this is a separate variable within the program that determines if it is image1.png, image2.png etc)
file_path = os.path.join(current_dir, "Program folder", "stuff", "content")
images_path = os.path.join(file_path, "images")
new_images_path = os.path.join(current_dir, "My Templates", anothervariable_name, "game", "template", "image_choices")
try:
shutil.copy(images_path + "\\" + filetocopy, new_images_path)
except:
print("error")
(folders listed in this have been checked if existing and placed if not - but not for the new file path due to that needing to be in a specific place within the main folder)
It either works if I have the files set up just right (for my own machine which defeats the purpose) or it doesn't do anything or I get an error saying the path doesn't exist. I have code prior to this that creates the folders needed but I'm trying to grab images from the folder that belongs to the actual program and put them (only ones I specify) into a new folder I create through the program.
Would i use os.walk? I was looking at all the os code but this is my first time dealing with any of it so any advice is helpful.
I'm trying to build a file transfer system with python3 sockets. I have the connection and sending down but my issue right now is that the file being sent has to be in the same directory as the program, and when you receive the file, it just puts the file into the same directory as the program. How can I get a user to input the location of the file to be sent and select the location of the file to be sent to?
I assume you're opening files with:
open("filename","r")
If you do not provide an absolute path, the open function will always default to a relative path. So, if I wanted to open a file such as /mnt/storage/dnd/5th_edition.txt, I would have to use:
open("/mnt/storage/dnd/4p5_edition","r")
And if I wanted to copy this file to /mnt/storage/trash/ I would have to use the absolute path as well:
open("/mnt/storage/trash/4p5_edition","w")
If instead, I decided to use this:
open("mnt/storage/trash/4p5_edition","w")
Then I would get an IOError if there wasn't a directory named mnt with the directories storage/trash in my present folder. If those folders did exist in my present folder, then it would end up in /whatever/the/path/is/to/my/current/directory/mnt/storage/trash/4p5_edition, rather than /mnt/storage/trash/4p5_edition.
since you said that the file will be placed in the same path where the program is, the following code might work
import os
filename = "name.txt"
f = open(os.path.join(os.path.dirname(__file__),filename))
Its pretty simple just get the path from user
subpath = raw_input("File path = ")
print subpath
file=open(subpath+str(file_name),'w+')
file.write(content)
file.close()
I think thats all you need let me know if you need something else.
like you say, the file should be in the same folder of the project so you have to replace it, or to define a function that return the right file path into your open() function, It's a way that you can use to reduce the time of searching a solution to your problem brother.
It should be something like :
import os
filename = "the_full_path_of_the_fil/name.txt"
f = open(os.path.join(os.path.dirname(__file__),filename))
then you can use the value of the f variable as a path to the directory of where the file is in.
Guten tag everybody.
I'm new to Python and am trying to re-create a simple mp3 player.
When I run the code below the UI pops up and asks for a directory, but when I navigate to where my mp3 files are located I get the message "no items match your search". I can navigate to and play all my files without issue through normal file explorer.
When I click on cancel, I get the error "OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '' "
I'm on a Windows 10 machine, using Python 3.6. I'm using Sublime with Anaconda to run the code.
I have looked through google, stack, youtube, documentation and can't figure out what I'm doing wrong. Thanks in advance for your help.
import os
import pygame
import tkinter
from tkinter.filedialog import askdirectory
root = tkinter.Tk()
root.minsize(300, 300)
songList = []
index = 0
def directorychooser():
directory = askdirectory()
os.chdir(directory)
for files in os.listdir(directory):
if files.endswith('mp3'):
songList.append(files)
print("songList")
directorychooser()
Could you check if the path you are choosing is an absolute (starting with 'C:\') or relative path. If it's absolute it should work.
However if it's relative (for example 'Music' in the current folder), changing directory (chdir) before listing will not work. You should print it.
You should try to remove the os.chdir call which is not required except in very specific cases.
You can also change the path to an absolute path:
directory = os.path.abspath(directory)
Before doing the os.chdir of course.
For the cancel case, you should verify it the directory exists (It will return None if you hit cancel):
if directory:
<Look for files>
I would like to open a file dialog with easygui but the path contains a folder with a .: C:\Users\user\.atom
myfile= easygui.fileopenbox(msg="Choose a file", default=r"C:\Users\user\.atom")
This opens the dialog box to C:\Users\user not C:\Users\user\.atom
I didn't / don't use easygui, just looked at the source code.
easygui does some path processing on the default argument. That processing involves [Python]: os.path.split(path) which splits the path in 2 parts (what comes before and after the last path separator (bkslash or "\")).
Since ".atom" comes after the last "\", it's not considered as part of the path (the fact that it contains a "." is just a coincidence and has nothing to do with it).
To fix your problem, add a wildcard to your path, e.g.:
myfile = easygui.fileopenbox(msg="Choose a file", default=r"C:\Users\user\.atom\*")
Another solution is to end default with two \\:
r"C:\Users\user\.atom\\"