我几天在Windows 7上修补Python 3.66。取得了良好的进展, 但我完全不知道如何使用我想要的文件夹内容显示打开Windows资源管理器。
我在这里尝试了至少7种不同的相关问题的解决方案,但似乎都没有效果。他们都打开资源管理器,但从未使用我的Folder_selected 变量
资源管理器位是最后一行代码。 这是(我怀疑的编码很糟糕)来源:
#FRenum-v.04
#renumbers a folder of files to 01 onward preserving file extenders.
#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)
#path is now the dir
path=(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 extender 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 extender
created_file=("0"+str(inc)+ file_ext)
#if file does not exist 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
#open explorer showing folder of renamed files
subprocess.Popen(["C:\\Windows\\explorer.exe"])
#these do not work properly, opens in c: or my docs
#subprocess.Popen(["C:\\Windows\\explorer.exe"+ folder_selected])
#subprocess.Popen(["C:\\Windows\\explorer.exe", folder_selected])
#subprocess.Popen(["C:\\Windows\\explorer.exe","folder_selected"])
#todo
#---------
#ignore sub-folders
#confirm requestor
#undo feature
#find out how to stop dos box showing in compiles prg
答案 0 :(得分:0)
所以,你的程序是完美的,只是由于某种原因在路径中使用了错误的斜杠,python显然可以处理,但explorer.exe不能。
我运行了你的程序,并打印出folder_selected
,我得到了C:/Users/Michael/Desktop/test
。其中包含正斜杠,而windows路径则使用反斜杠
我只想将subprocess.Popen(["C:\\Windows\\explorer.exe"])
替换为:subprocess.Popen(["C:\\Windows\\explorer.exe", folder_selected.replace('/', '\\')])
这将替换任何带有反斜杠的正斜杠,explorer.exe应该能够处理
希望这有效:)
Windows路径也不能有任何斜杠,因此用户不会有一个包含任何/
的目录,因此replace
应该没问题
答案 1 :(得分:0)
这个问题是由python / linux和表示路径的窗口之间的差异引起的。
我打印了folder_selected
并获得了:
C:/Users/name/Documents/Zevel
您需要在致电askdirectory()
后添加以下内容:
folder_selected = folder_selected.replace('/', '\\')
使窗口的路径可读,现在看起来像:
C:\Users\name\Documents\Zevel
当然你需要打电话subprocess.Popen(["explorer", folder_selected])
,一切都会奏效。