2016-08-25 112 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

相關問題