How to replace input string in python - python

I use tkinter make interface to select folder directory and i get C:/Users/dtung/Desktop/ and i want to convert it to C:\Users\dtung\Desktop\ because i use autoit to select file. this is my code
import_file_path = filedialog.askdirectory()
list = os.listdir(path=import_file_path)
import_file_path.replace("/","\\")
replace function does't work with any string or character(dont have any error it just does't work), when i print it out i just received old string.

I don't understand your problem. The code above works fine for me.
import os
from tkinter import filedialog
import_file_path = filedialog.askdirectory()
list = os.listdir(path=import_file_path)
print('Before', import_file_path)
import_file_path = import_file_path.replace("/", os.sep)
print(os.path.join(import_file_path))
print('After', import_file_path)
prints out this on my Windows machine
Before C:/Users/Mega/Documents/HuaweiMusic
C:\Users\Mega\Documents\HuaweiMusic
After C:\Users\Mega\Documents\HuaweiMusic
By the way, why do you need to mix Autoit and Python?

You can use this code to fix the problem:
import os
from tkinter import filedialog
import_file_path = filedialog.askdirectory()
list = os.listdir(path=import_file_path)
import_file_path = import_file_path.replace("/", "\\")

Related

Creating a subfolder in a folder opened with filedialog

I am currently trying to make a program for file organisation. I want my script to open a filedialog that asks for a sourcefolder where the files will be organised in based on their extension. After a sourcefolder has been selected, I want my script to make directories in that sourcefolder. I am a bit stuck on that last part.
import os
import shutil
from os import listdir
from os.path import isfile, join
import tkinter as tk
from tkinter import filedialog
from tkinter import *
print('This is a program that organises files in a given directory')
print(''
'')
print('Please select the folder in which you want to organise your files')
''' Source Folder '''
root = Tk()
root.withdraw()
source_path = filedialog.askdirectory()
The part above works just fine.
''' Create destination folders in the source folder '''
newpath1 = r'source_path\Images'
if not os.path.exists(newpath1): # check to see if they already exist
os.makedirs(newpath1)
newpath2 = r'source_path\Documents'
if not os.path.exists(newpath2):
os.makedirs(newpath2)
newpath3 = r'source_path\Else'
if not os.path.exists(newpath3):
os.makedirs(newpath3)
This, however, does not. It just removes files, or places them somewhere I cannot find them.
Any help would be greatly appreciated.
TLDR: how to make directories in a sourcefolder submitted with filedialog.

Cannot read a list of pictures cv2.imread()

I am new in programming, and I would like to make a picture resizer with gui.
I have problems with making the gui.
I grabbed the problematic part of the code:
from tkinter import *
from tkinter import filedialog
import os, backend, glob2, cv2
loaded_pics=[]
picture_read=[]
window = Tk()
browsed_dir = StringVar()
browsed_dir.set(filedialog.askdirectory(initialdir="/",title='Please select a directory'))
file_path = browsed_dir.get()#+"/"
for filename in os.listdir(file_path):
if filename.endswith(('.jpg', '.jpeg', '.gif', '.png')):
loaded_pics.append(filename)
print(loaded_pics)
try:
for images in loaded_pics:
imgs = cv2.imread(images, 1)
print(imgs)
except:
print("ERROR")
window.destroy()
window.mainloop()
So, I have got a list of .png/.jpg/.bmp files, I can print the list, but I cannot read them with cv2.imread(), when I print(imgs), I got "None"-s.
(I have not managed to make this with glob2. It is work well with current directory, but I could not make it with filedialog.)
I hope someone can help.
Thanks in advance!
You are building a list of filenames in loaded_pics. But this doesn't include the name of the directory, file_path. So when you call imread, your image is actually located at file_path/filename, but you are only passing filename. So cv2 cannot find your file, and returns None.

Drag-and-Drop multiple files in Python (Windows)

I'm starting to learn Python, and I thought to create a converter from a file to another (for example, from png to avi or between other file extensions) under Windows OS for now.
I wrote a script which works fine and it completes the conversion process, but I want improve it in functionality (and then in graphics); I'm using Tkinter and I thought to load the files with the possibility to drag-and-drop them as input for the next conversion command, instead of open a folder in which to put files as "input source". I found this topic (python drag and drop explorer files to tkinter entry widget) and I used it in this way:
import sys
import os
import Tkinter
from tkdnd_wrapper import TkDND
import shlex, subprocess
from subprocess import Popen, PIPE
import glob
import shutil
root = Tkinter.Tk()
dnd = TkDND(root)
entry = Tkinter.Entry()
entry.grid()
def handle(event):
inputfilespath = event.data
event.widget.insert(0, inputfilespath)
filesdir = os.path.dirname(os.path.realpath(inputfilespath))
files = glob.iglob(os.path.join(filesdir, "*.myext"))
for inputfilespath in files:
if os.path.isfile(inputfilespath):
subprocess1 = subprocess.Popen([...conversion command given as list, not string...], shell=True)
print "\n\nConversione in corso..."
subprocess1.wait()
subprocess1.terminate()
print "\n\nProcesso terminato!"
dnd.bindtarget(entry, handle, 'text/uri-list')
root.mainloop()
The problems:
If filename has a space, there is no conversion, and process ends without even notify any error too. "inputfilespath" wants to be the generic name for all the input files which I selected, and (for what I read) I can't (?) use quotes for an environment variable hoping to include filename's whitespace...
I tried to copy different files (with the same file extension and without whitespaces into the filename) in the same folder, and if I drag-and-drop only one of them on the Entry widget, the process starts fine (and this is great!), but it continues also for all the other no-selected files with the same extension in the same folder, whereas if I drag-and-drop multiple files on the Entry widget, no conversion occurs....
It seems that filenames containing whitespace are being wrapped in braces
(Tcl list style). To get a usable filelist, you should be able to do
something like:
import Tkinter
from untested_tkdnd_wrapper import TkDND
def handle(event):
files = root.tk.splitlist(event.data)
for filename in files:
event.widget.insert('end', filename)
root = Tkinter.Tk()
lb = Tkinter.Listbox(root, width=50)
lb.pack(fill='both', expand=1)
dnd = TkDND(root)
dnd.bindtarget(lb, handle, 'text/uri-list')
root.mainloop()
Just use the tkinter file dialog, then just have it insert the files into the entry box.
Example:
filedialog = tkFileDialog.askopenfilenames(*options*)
entry.insert(END, filedialog)
Example Using StringVar:
entryVar = StringVar()
entry = Entry(textvariable=entryVar)
filedialog = tkFileDialog.askopenfilenames(*options*)
entryVar.set(filedialog
Hope this helps!

Python; User Prompts; choose multiple files

I would like to have my code bring up a window where you can select multiple files within a folder and it assigns these filenames to elements of a list.
Currently, I can only select a single file at a time and it assigns the filename to a single variable.
from Tkinter import Tk
from tkFileDialog import askopenfilename
Tk().withdraw()
filename = askopenfilename()
Thank you.
You need to use the askopenfilenames method instead.
You can encapsulate all that in a function:
def get_filename_from_user(message):
root = Tk()
root.withdraw()
filename = tkFileDialog.askopenfilename(title=message)
return filename
Then you can call it as many times as you like:
filename1 = get_filename_from_user('select the first file!')
filename2 = get_filename_from_user('select another one!')
filename3 = get_filename_from_user('select one more!')
Unless you have tons of files you want to select. Then you probably want to use askopenfilenames:
files = tkFileDialog.askopenfilenames(parent=root,title='Choose a file or LOTS!')
from easygui import fileopenbox
files = []
#how many file you want choice
fileCount = int(input("How many file need open"))
for x in range(fileCount):
files.append(fileopenbox())
print(files)

Python: easygui, how to select multiple files?

I am using fileopenbox() and I want to select all text files I have when the windows box is open. I have tried to press shift or ctrl + A, but it didn't work.
openfile = fileopenbox("Welcome", "COPR", filetypes= "*.txt")
You can select multiple files if you include multiple=True in the arguments:
openfiles = fileopenbox("Welcome", "COPR", filetypes= "*.txt", multiple=True)
Note that now fileopenbox will return not a string, but a list of strings like:
["foo.txt", "Hello.txt", "mytxt.txt"]
another option could be using tkinter as follows(python 3.x):
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
files = filedialog.askopenfilenames(parent=root, initialdir="/", title='Please select files')
It's not possible with easygui. What you can do is reuse the code from easygui (see line 1700) and modify it slightly to use askopenfilenames instead of askopenfilename.

Categories

Resources