Python 创建目录或文件路径列表
我正处于python教育的早期阶段 我正在尝试创建一个从用户输入中获取的目录列表 我不确定列出目录的语法是什么 以下是我到目前为止的情况:Python 创建目录或文件路径列表,python,list,Python,List,我正处于python教育的早期阶段 我正在尝试创建一个从用户输入中获取的目录列表 我不确定列出目录的语法是什么 以下是我到目前为止的情况: import os from Tkinter import * import tkMessageBox master = Tk() master.geometry("600x100+700+400")#remember its .geometry("WidthxHeight(+or-)X(+or-)Y") filePath = Label(text
import os
from Tkinter import *
import tkMessageBox
master = Tk()
master.geometry("600x100+700+400")#remember its .geometry("WidthxHeight(+or-)X(+or-)Y")
filePath = Label(text="Enter filepath of files to convert")
filePath.pack()
e = Entry(master,width=60)
e.pack()
e.focus_set()
def convert():
myDirectory = e.get()
filepaths= '['+e.get()+']'
for i in filepaths:
filesToChange=os.listdir(i)
for f in filesToChange:
cmd = '/Applications/OpenImageIO/dist/macosx/bin/iconvert --inplace --scanline --compression zip -d half ' + os.path.join(i,f)
os.system(cmd)
def happyComp():
window = Tk()
window.wm_withdraw()
window.geometry("1x1+200+200")#remember its .geometry("WidthxHeight(+or-)X(+or-)Y")
tkMessageBox.showerror(title="Happy Compositing!",message="Converted!",parent=window)
def click():
convert()
happyComp()
b = Button(master, text="convert now!!!", width=10, command=click)
b.pack()
mainloop()
用户将在文本字段中输入多个用逗号分隔的目录。到目前为止,python似乎将文件路径中的每个字母都视为列表的一部分。。。是否要让它将每个文件路径视为文件路径?在python中,如果将字符串传递给for循环(例如,“hello”中的for i:),它将分别返回每个字母。我想您需要的是filepath.split(“,”中的I
,它将接受字符串并用逗号将其拆分。您可能还想:
在循环中调用strip(例如,filepath=i.strip()
)(如果用户放置的是dir1、dir2、dir3而不是dir1、dir2、dir3)
检查您得到的是一个文件(可能是一个图像或其他);我相信os.listdir会回来的。和。。关于unixy系统;如果您知道自己拥有所有.jpg,那么一个简单的检查就是if f.endswith(“.jpg”)
)
编辑:删除了第3点,注意到您确实在屏幕外使用了os.path.join*我只看到变量filePath
已定义,filePath
从何而来?*e.pack
行做什么?它转换变量了吗?*convert
是如何调用的?哎呀,我没有复制所有内容,这是整个脚本。非常感谢,效果非常好!我将开始研究您的其他建议以改进我的代码。我是否会将:for I放入directories.split(“,”):I.strip(“”)filesToChange=os.listdir(I)