2009-11-17 28 views
1

我有一個腳本在USB驅動器上創建一個名爲「videos」的文件夾,將6,500個WMV文件移動到「videos」文件夾中。然後它假設創建一個帶有超鏈接到每個文件的HTML頁面。這是我現在的例子。我試圖讓它抓取視頻目錄,並創建一個HTML頁面,其超鏈接僅適用於USB驅動器上的本地文件。Python - 使用os.listdir超鏈接創建html頁面

#!/usr/bin/python 
import os.path 
import os 
import shutil 
import re 

# Create the videos directory in the current location 
# If the directory exists ignore it 
def createDirectory(): 
    directory = "videos" 
    if not os.path.isdir("./" + directory + "/"): 
     os.mkdir("./" + directory + "/") 
     print "Videos Folder Created." 
    else: 
     print "Video Folder Exists." 
     print "---------------------" 

# Move all the files in the root directory with the .wmv extension 
# to the videos folder 
def moveVideos(): 
    for file in os.listdir("."): 
     if os.path.splitext(file)[1] == ".wmv": 
      print "Moving:", file 
      shutil.move(file, os.path.join("videos", file)) 

def createHTML(): 
    videoDirectory = os.listdir("videos") 
    f = open("videos.html", "w") 
    f.writelines(videoDirectory) 
    r = re.compile(r"(\\[^ ]+)") 
    print r.sub(r'<a href="\1">\1</a>', videoDirectory) 

createDirectory() 
moveVideos() 
createHTML() 
+2

以何種方式是它壞了? – stimms 2009-11-17 15:50:22

+0

html頁面是否應該在文件的「videos」目錄中? – ntownsend 2009-11-17 16:13:33

回答

1

不要做f.writelines(videoDirectory)然後正則表達式。除此之外,您只能使用該正則表達式替換打印到控制檯。

videoDirectory = os.listdir("videos") 
f = open("videos.html", "w") 
f.write('<html><head></head><body><ul>'  
f.writelines(['<li><a href="videos/%s">%s</a></li>' % (f, f) for f in videoDirectory]) 
f.write('</ul></body></html>') 
+0

這一個爲我工作,感謝所有給我正確的方向。 – Dunwitch 2009-11-19 15:57:05

9
import cgi 

def is_video_file(filename): 
    return filename.endswith(".wmv") # customize however you like 

def createHTML(): 
    videoDirectory = os.listdir("videos") 
    with open("videos.html", "w") as f: 
    f.write("<html><body><ul>\n") 
    for filename in videoDirectory: 
     if is_video_file(filename): 
     f.write('<li><a href="%s">%s</a></li>\n' % 
       (cgi.escape(filename, True), cgi.escape(filename))) 
    f.write("</ul></body></html>\n") 
+0

+1:這比扔正則表達式要簡單得多。 – 2009-11-17 15:57:59

+1

+1正確逃脫 – digitalarbeiter 2009-11-17 15:59:26

0
def createHTML(): 
    h = open("videos.html", 'w') 
    for vid in os.listdir: 
     path = "./videos" + vid 
     f = open(path, r) 
     h.write("<a href='"+f.name+"'>"+f.name[f.name.rfind('\\') +1 :]+"</a>") 
     f.close() 
    h.close() 
    print "done writing HTML file"