2016-08-25 29 views
0

我有一个python脚本,可以在循环中截取屏幕截图并保存所有这些图像。不过目前,所有图像都存储在Python35文件夹中。Python - 如何使用用户输入的名称创建文件夹?

因此,我希望用户输入文件夹的名称并通过此名称创建一个名称。

我知道使用makedirs函数并指定一个路径newpath=r'C:/users/../'

但是,如何将用户指定的新文件夹名添加到路径中?

(EDIT)这里是我的代码有: -

import openpyxl 
import re 
import os 
import time 
from PIL import ImageGrab 
import webbrowser 

source_excel=input('Enter the source excel file name-> ') 
wb=openpyxl.load_workbook(source_excel) 
sheet=wb.active 


strt=int(input('Enter starting range-> ')) 
end=int(input('Enter ending range-> ')) 

#NEED THE CHANGE HERE 

foldname=input("Enter a folder name to create where images will be saved") 
newpath=r'C:\Users\rnair\AppData\Local\Programs\Python\Python35\'demofile 


# Loop to get the link from excel and take the screenshot by opening the browser for each link 

for q in range(strt,end): 
    getme=q,sheet.cell(row=q,column=1).value  #get link from excel file  
    ab=getme[1] 
    #myopener=Myopen() 
    rowc=str(strt) 
    url=ab 
    webbrowser.open(url)       #opens browser for the link fetched 

    time.sleep(7)         # Delay to wait for the page to load completely 
    im=ImageGrab.grab() 
    os.chdir(newpath) 
    im.save("Row"+rowc+".jpg","JPEG")    # Saving image to file 
    strt=strt+1 
+2

查看https://docs.python.org/3/library/pathlib.html和https://docs.python.org/3/library/os.path.html。没有看到你的实际代码和适当的问题陈述,很难说更多。 –

+0

@Ro_nair Python中的反斜杠将转义跟随它的引号(所有其他内容),所以如果您使用Windows路径,请使用双斜杠(相当于单个转义斜线)。除此之外,您的代码不会运行,因为您的'newpath'赋值中的转义引用会创建一个未终止的字符串;修复这个问题是不够的,因为之后会立即出现语法错误,因为'demofile'既没有定义也没有被任何操作符从字符串中分离出来。 – kungphu

回答

3

如果你的意思是建立在该文件应保存的路径,使用os.path.join与基本目录第一和自定义目录名第二(文件名可以作为第三个参数提供)。只要非常小心信任用户输入任何东西,特别是文件系统操纵。

+0

@Ro_nair除了我在你的原帖的评论中提到的问题:建立你的最终路径的用法就像'os.path.join(basedir,foldname)'一样。 – kungphu

+0

谢谢你的一个很好的解释!我明白了一切,它就像你说的那样工作! –

+0

不客气。我很高兴它为你工作。 :) – kungphu

相关问题