I'm trying to create a script where the user can select 1 or all files in a folder (to "imitate" the multi-selection open of uigetfile in Matlab). Afterwards, the script will ask if the user wants to import data from another location and the import 1 or all routine continues.
The mission of the script is just to retrieve the path and file names for a multi-selection option. It was written on a PC using Windows 10, with Python 3.6 and Spyder as a IDE in the Anaconda Distro.
So far I have this:
def import_multiple_files():
# Similar to UIGETFILE
import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox
import glob
root = tk.Tk()
root.withdraw()
root.attributes("-topmost", True)
root.lift()
file_location = filedialog.askopenfilename()
a=file_location.split('/')
path=[]
for i in range(0,len(a)-1):
path.append(a[i])
path= "/".join(path)
filename=a[len(a)-1]
# Questions the user
qst=messagebox.askyesno("Multiple Import","Do you want to import all .txt files in this folder?")
allFiles=[]
if qst==True:
# Gets all .txt files in path FOLDER
b=glob.glob(path + "/*.txt") # glob. lists the filename and path
allFiles.append(b)
else:
b=(path + "/"+ filename)
allFiles.append(b)
qst=messagebox.askyesno("Multiple Import","Do you want to import more DATA?")
finish=0
while finish==0:
if qst==True:
# deletes all variables except "AllFILES" (location of all files to import)
del(root,file_location,a,path,qst,b)
root = tk.Tk()
root.withdraw()
root.attributes("-topmost", True)
root.lift()
file_location = filedialog.askopenfilename()
a=file_location.split('/')
path=[]
for i in range(0,len(a)-1):
path.append(a[i])
path= "/".join(path)
filename=a[len(a)-1]
qst=messagebox.askyesno("Multiple Import","Do you want to import all .txt files in this folder?")
if qst==True:
# Gets all .txt files in path FOLDER
b=glob.glob(path + "/*.txt")
allFiles.append(b)
qst=messagebox.askyesno("Multiple Import","Do you want to import more DATA?")
else:
b=(path + "/"+ filename)
allFiles.append(b)
qst=messagebox.askyesno("Multiple Import","Do you want to import more DATA?")
else:
finish=1
return(allFiles)
file_location=import_multiple_files()
The script/function returns the full path and file name, however, some of the names came with a double backslash for some reason
e.g,
file_location
[['C:/Users/user/Desktop/New Folder (2)\\1.txt',
'C:/Users/user/Desktop/New Folder (2)\\2.txt',
'C:/Users/user/Desktop/New Folder (2)\\3.txt'],
['C:/Users/user/Desktop/New Folder (3)/1.txt']] # For this last file, I did not select the option of importing all files.
Can anyone be so kind as to take a look to this script and see if something is wrong, or if this is just the way Python displays things.
Thank you in advance!
The \\ is just the way Python shows an escaped backslash. \ is used in a number of contexts for signifying a new line (\n), a tab (\t) etc. So \\ just indicates that whatever appears after the backslash is not one of these special characters.
Python will make sense of your mixture of forward and backslashes but if you want to have everything display consistently, you can use [os.path.abspath(d) for d in my_list].
Also, it looks like you should be using extend instead of append if you want to avoid creating a list of lists.
Here is the "final" version
Thank you all!
This function retrieves the file location of 1 or all files in a folder.
def import_multiple_files():
# 'similar' to UIGETFILE
import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox
import glob
import os
# Creates a Tkinter window to search for a file
root = tk.Tk()
root.withdraw()
root.attributes("-topmost", True)
root.lift()
file_location = filedialog.askopenfilename()
a=file_location.split('/')
# Separates the file location into path and file name
path=[]
for i in range(0,len(a)-1):
path.append(a[i])
path= "/".join(path)
filename=a[len(a)-1]
# Questions the user
qst=messagebox.askyesno("Multiple Import","Do you want to import all .txt files in this folder?")
allFiles=[]
if qst==True:
# Gets all .txt files in path FOLDER
b=glob.glob(path + "/*.txt")
allFiles.extend(b)
else:
b=[(path + "/"+ filename)]
allFiles.extend(b)
# Questions the user
qst=messagebox.askyesno("Multiple Import","Do you want to import more DATA?")
# Allows the user to import as many files from as as many folders as he/she chooses
finish=0
while finish==0:
if qst==True:
# deletes all variables except "AllFILES" (location of all files to import)
del(root,file_location,a,path,qst,b)
root = tk.Tk()
root.withdraw()
root.attributes("-topmost", True)
root.lift()
file_location = filedialog.askopenfilename()
a=file_location.split('/')
path=[]
for i in range(0,len(a)-1):
path.append(a[i])
path= "/".join(path)
filename=a[len(a)-1]
qst=messagebox.askyesno("Multiple Import","Do you want to import all .txt files in this folder?")
if qst==True:
# Gets all .txt files in path FOLDER
b=glob.glob(path + "/*.txt")
allFiles.extend(b)
qst=messagebox.askyesno("Multiple Import","Do you want to import more DATA?")
else:
b=[(path + "/"+ filename)]
allFiles.extend(b)
qst=messagebox.askyesno("Multiple Import","Do you want to import more DATA?")
else:
finish=1
b=[os.path.abspath(d) for d in allFiles]
# Returns all file locations
return(b)
Related
Goal: Clean up duplicate data for specified file types in a drive. Amongst a series of duplicates, the file that remains should be the most recently modified.
Problem: It removes duplicates, but it does not discriminate by modified date/time.
I got this code from G4G. I've only added the "if file.endswith" part.
https://www.geeksforgeeks.org/deleting-duplicate-files-using-python/
from tkinter.filedialog import askdirectory
# Importing required libraries.
from tkinter import Tk
import os
import hashlib
from pathlib import Path
import time
# We don't want the GUI window of
# tkinter to be appearing on our screen
Tk().withdraw()
# Dialog box for selecting a folder.
file_path = askdirectory(title="Select a folder")
# Listing out all the files
# inside our root folder.
list_of_files = os.walk(file_path)
# In order to detect the duplicate
# files we are going to define an empty dictionary.
unique_files = dict()
for root, folders, files in list_of_files:
# Running a for loop on all the files
for file in files:
# Finding complete file path
file_path = Path(os.path.join(root, file))
# Converting all the content of
# our file into md5 hash.
Hash_file = hashlib.md5(open(file_path, 'rb').read()).hexdigest()
# If file hash has already #
# been added we'll simply delete that file
if Hash_file not in unique_files:
unique_files[Hash_file] = file_path
else:
if file.endswith((".txt",".bmp")):
os.remove(file_path)
print(f"{file_path} has been deleted")
Bonus Problem: In a drive that I am clearing of duplicates, there are 1148 folders. However, I do not want duplicates between the immediate different folders in the drive to be considered for removal. Is there a way to iterate this script over each folder instead of selecting each folder one by one?
i'm trying to code a patch programs with python to move translation files into the game.
i was able to make a program to select the file, but i'm suffering to move that selected file to the designated destination.
it says that python could not find the file "files", but i couldnt find the solution how to make it read the file.
import shutil
import os
from tkinter import filedialog
from tkinter import messagebox
list_file = []
files = filedialog.askopenfilenames(initialdir="/",\
title = "Select file")
if files == '':
messagebox.showwarning("Warning", "Add the file.")
destination = r'C:\Program Files (x86)\Steam\steamapps\common\I Wanna Maker\locale'
shutil.move("files", "destination")
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.
In Tkinter, I have to just select the folder in which my files are present. I am doing it using filedialog.askdirectory().
Is it also possible to view the files present in the folder in UI ?
Use this function by provide a file extension (any extension should be fine)!
file_extension="niff"
def displayall ( file_extension):
root = Tk()
root.withdraw()
path = filedialog.askdirectory()
# get data file names, all the file extention
os.chdir(path)
all_fNames0 = glob.glob(path + '/**/*.{}'.format(file_extension), recursive=True)
print("Total number of files:", len(all_fNames0))
print("All file names:", all_fNames0)
Hope this helps!
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))]