Cutting Strings Pyhton


i have a simple ui created with pyqt5

it loads a file, let you choose a outputfolder and creats a new txt file with additonals information.

the string of the loaded file is written to


it looks like "C:/User/Folder/File.txt"

later in the application i write into a new file in a specific location.

new_txt = open(self.inputs.foldername.text() + "/optimized.txt", "w")

I want to add the "optimized.txt" string to the orginal Filename. But if I use self.inputs.filename.tex() it gives back the whole path and creates an error. I tried it with .removesuffix() but since the Path is always variable I cant find a solution to just keep the character after the last "/".

Please dont lynch me I’m quite new to python.

>Solution :

You can use the split function of a string to get the element after the last ‘/’. Like this :

str_path = self.inputs.foldername.text()
split_text = str_path.split('/') #this give you a list of str element splitted by the character '/'
last_element = split_text[-1]

Now you can use the last element that should contains ‘File.txt’. you can split it again respect to "." and get only the name of the file without the .txt extension.

Hope I answered you question.

Leave a ReplyCancel reply