Python; User Prompts; choose multiple files - python

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)

Related

How to add value in a table using Tkinter

The aim of this code is to select a file then add it to a table and in the next column it should display the file format. Example:
[File Name] [File Format]
[candy.csv] [a csv file]
[corona.txt] [a txt file]
[computer.json] [a json file]
I know how to select files and i know how to create a table, but I am having trouble to make the two work together. I am new to python.
This is the code to select all the files in a specific folder
def browse():
os.chdir("/home/amel/Downloads/Corona")
for file in glob.glob("*.*"):
s = file
print(s)
folder_path = str(s)
tx.insert(END, folder_path + '\n')
return s
Try using os module to split pathfilename into components.
Taking your code snippet and expanding it to include a key binding <Control-g> that calls function browse.
This splits pathfilename into path, filename and then filename into name, ext.
filename and ext are inserted into tk.Text to produce an appropriate list.
import tkinter as tk
import os, glob
root = tk.Tk()
tx = tk.Text()
tx.grid()
# select your own path
pathname = os.getcwd()
def browse(ev):
os.chdir(pathname)
for file in glob.glob("*.*"):
path, filename = os.path.split(file)
name, ext = os.path.splitext(filename)
tx.insert(tk.END, f"[{filename}] [{ext}]\n")
root.bind("<Control-g>", browse)
root.mainloop()

Beginner:Python 3.66. Win7. How do I ignore sub-folders in this code?

Can anyone tell me how I can get the for loop at the end of this program
NOT to rename folders, only files? I'm at a loss on this one.
I'm assuming the command to use is if os.path.isdir(file)
but I cant seem to get it to work no matter where I put it, same goes for os.path.isfile().
I'm still at the stage (my first week) where I am confused by most commands and functions, though I did dabble in ZX BASIC\AMOS and STOS in the 80s\90s so I have a rudimentary understanding of variables etc.
#FRenum-v.05
#renumbers a folder of files 01 onward preserving file extensions.
#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)
# 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 extension 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 ext
created_file=("0"+str(inc)+ file_ext)
#if filename does not already exist then 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
#Display contents of folder in explorer
#https://stackoverflow.com/questions/50892257/beginner-opening-explorer-to- show-folder-contents
subprocess.Popen(["C:\\Windows\\explorer.exe", folder_selected.replace('/', '\\')])
#thanks to Michael for this line if code
load the modules can add it at the beginning of the script
from os.path import join , isfile
add this line before the loop:
files = [filenames for filenames in files if isfile(join(folder_selected, filenames))]

How to randomly select a file in python

I am intermediate when it comes to python but when it comes to modules I struggle. I'm working on a project and I'm trying to assign a variable to a random directory or file within the current directory (any random thing within the directory). I would like it to just choose any random thing in that directory and then assign it to a variable.
The product should end up assigning a variable to a random object within the working directory. Thank you.
file = (any random file in the directory)
Edit: This works too
_files = os.listdir('.')
number = random.randint(0, len(_files) - 1)
file_ = _files[number]
Thank you everyone that helped :)
Another option is to use globbing, especially if you want to choose from some files, not all files:
import random, glob
pattern = "*" # (or "*.*")
filename = random.choice(glob.glob(pattern))
You can use
import random
import os
# random.choice selects random element
# os.listdir lists in current directory
filename=""
# filter out directories
while not os.path.isfile(filename):
filename=random.choice(os.listdir(directory_path))
with open(filename,'r') as file_obj:
# do stuff with file
_files = os.listdir('.')
number = random.randint(0, len(_files) - 1)
file_ = _files[number]
Line by line order:
It puts all the files in the directory into a list
Chooses a random number between 0 and the length of the directory - 1
Assigns _file to a random file
Here is an option to print and open a single random file from directory with mulitple sub-directories.
import numpy as np
import os
file_list = [""]
for root, dirs, files in os.walk(r"E:\Directory_with_sub_directories", topdown=False):
for name in files:
file_list.append(os.path.join(root, name))
the_random_file = file_list[np.random.choice(len(file_list))]
print(the_random_file)
os.startfile(the_random_file)

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: 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