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>
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 am doing a project using python in which I got stuck at a point where I want to access some text files which are saved outside the project directory.
The path where my text files are saved:
C:\Users\saqibshakeel035\Desktop\Scientific Project Lithim battery project\text_file_r_w
The path of my python project:
C:\Users\saqibshakeel035\PycharmProjects\Tutorial_1
I want to open/read my text files (external > not included in python project folder)
I already know the Reading/writing etc etc within the same folder where the python project .py file is present but struggling with the different paths.
I tried:
import os
from os import path
print("Your cunrrent directory is : %s" %path.curdir)
strpath = r"C:\Users\saqibshakeel035\Desktop\Scientific Project Lithim battery project\text_file_r_w"
print("Your current directory is %s: " %path.dirname(strpath))
print("Your current directory is : %s" %path.abspath(strpath))
This works fine and it shows my abspath where my text files are stored but when I try to read it with the following command
f = open("file1.txt","r")
It gives error that no such directory or file found
I suggest you try f = open("C:/text/to/path/file1.txt","r") or the code #Jaba has mention. Either works fine
Can you try using the full path to "file1.txt" in the open function.
f = open("Full_path_to_file1.txt", "r")
Another option is to change the current directory,
os.chdir(path)
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.
I am using python on mac and would like to open a pdf file that is present in different directory than the directory my main python code is running. I tried different options but there is always an error saying file doesn't exist even when the file is present or [Error no. 2] file cannot be opened. Here is the code that I use:
helpFile = os.path.abspath('~/help/help.pdf')
self.help_btn = tk.Button(self.help_frm, text="Help!", width=8, command = lambda: os.system("open "+helpFile))
could some one help please.
abspath does not expand ~ into the user's home directory, it just calculates the absolute path of a file based on its path relative to the current working directory.
From the docs, it is equivalent to:
normpath(join(os.getcwd(), path))
So in your code, helpFile is being set to "/path/to/cwd/~/help/help.pdf"
To expand ~, use os.path.expanduser.
I know this may sound really stupid, but how can I move a file in a directory a user browsed to ( I named mine filedir) to the current directory I am in?
for example: I have a file called "pages.html" in "C:\webs". How can I move that file to the current working directory "."?
This is my code:
shutil.move(filedir, "*.*")
#I got errors using this code..
Is there another way to say current directory, other than "." ?
The second argument of shutil.move specifies a directory, not a glob mask:
import os.path
shutil.move(os.path.join(filedir, "pages.html"), os.getcwd())
should work.
It would be very helpful if you posted the error message and the complete traceback. However, to get the current working directory you can use os.getcwd(). As long as filedir points to a file and not the directory this should work.
filedir = r"C:\webs\pages.html"
shutil.move(filedir, os.getcwd())