Home > Software engineering >  How do I get the path selected by the user in Explorer?
How do I get the path selected by the user in Explorer?

Time:06-04

I have a program that makes voice text using .txt ,but os.startfile doesn't let me select the file, hence get the path to it) I will be very grateful for your help!!

Как должно быть. enter image description here Как у меня) enter image description here

import os
import pyttsx3 as pyt
from gtts import gTTS

class DICTOR:

    def __init__(self, path):
        self.engine = pyt.init()

        #voices = self.engine.getProperty('voices') 
        self.engine.setProperty('voice', 0)

        #rate = self.engine.getProperty('rate')
        self.engine.setProperty('rate', 150)

        with open(path, 'r') as file:
            self.file = file.read()
    
    # def speak(self):
    #     self.engine.say(self.file)
    #     self.engine.runAndWait()

    def save(self, filename):
        tss = gTTS(text = self.file, lang='en')
        tss.save(filename)
        #rate = self.engine.getProperty('rate')

path = os.startfile(filepath = 'D:\Python\Road_map\DICTOR')

DICTOR(path).save('.mp3')

CodePudding user response:

I'm guessing your problem is with the formatting. You should add r to the start. It should be:

path = os.startfile(filepath = r"G:\EEGdatabase\6541455.docx")

the r is needed because \ is considered to be a special character by python. Another option is to escape \ with \\:

path = os.startfile(filepath = 'D:\\Python\\Road_map\\DICTOR')

More info in the docs.

Finally, since you haven't provided your error message, maybe this isn't your problem at all. If this doesn't fix it, add your error log so we know exactly what is going on.


Edit: It seems you have misunderstood the use of os.startfile. This function takes in something you need to "start", and starts it. So if you had said

os.startfile("something.pdf")

Then something.pdf will be opened in your default PDF software. If you instead passed in something like file.html, then this html file will be opened in your default web browser.

So you are now passing in D:\Python\Road_map\DICTOR, which is a folder, and the startfile function simply opens up that folder in Windows Explorer. A full reference for startfile can be found in the docs.

In any case, I don't think you need startfile at all. You need a file selector, which you can get using the Tkinter package. You can then say:

from Tkinter import Tk     # from tkinter import Tk for Python 3.x
from tkinter.filedialog import askopenfilename

Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file
print(filename)
path = filename

(Taken from https://stackoverflow.com/a/3579625/3730626)

  • Related