我對Python腳本編程相當陌生,我想驗證目錄和子目錄中的文件名。 驗證應區分大小寫。 我使用python 2.6.5 操作系統:WIN7和XP按標準驗證文件名
我提示以下用戶輸入:
prompt = "year"
year = raw_input(prompt)
prompt = "number"
number = raw_input(prompt)
在這裏,我想搜索/驗證下面的文件和文件夾存在,其文件名是正確的。
folderstructure:
..\foobar_(number)_version1\music
文件中的子文件夾「音樂」
(year)_foobar_(number)_isnice.txt
(year)_itis(number)hot_today.txt
(year)_anything_is(number)possible.txt
(year)_something_{idont_want_to_check_this_part}_(number)_canbe_anything.txt
需要注意的是,包括下劃線所有文字都是一樣的,因此,應該永遠是正確的,除了之間的事( ) 要麼 {}。 我想輸出結果到一個txt文件,該文件報告文件名是否正確。
實現這個最合乎邏輯的方法是什麼? 我已經閱讀了lib文檔fnmatch(.fnmatchcase),RE和os(.path.isfile),並在這裏查找了一些示例,但我無法弄清楚在哪裏以及如何開始。
任何人都可以指向正確的方向嗎?
只要我的腳本有工作基礎,我會發布我的代碼以供參考或幫助其他人。
[EDIT2]我的第一個非的Hello World腳本
import os
import re
#output :
file_out = "H:\\output.txt"
f_out = open(file_out, 'w')
print "-------start-script----------"
#input
prompt = "enter 4 digit year: "
year = raw_input(prompt)
prompt = "enter 2 digit number: "
number = raw_input(prompt)
print "the chosen year is %s" % (year)
print "the chosen number is %s" % (number)
f_out.write ("start log!\n")
f_out.write ("------------------------------------------\n")
f_out.write ("the chosen year is %s\n" % (year))
f_out.write ("the chosen number is %s\n" % (number))
#part i'm working on
print "end script"
f_out.write ("------------------------------------------\n")
f_out.write ("end script\n")
#close file
f_out.close()
嗨,謝謝你的回答。 但我想確保年份和號碼之間的一切都是正確的。例如,在文件「(年)_foobar_(number)_isnice.txt」中,也應檢查部分「_foobar_」和「_isnice.txt」。 因此,如果我有一個像「(年)_foobar_(number)_isbad.txt」的文件,它應該報告它是不正確的(因爲它不符合所需的部分「_isnice.txt」 希望我解釋得很對,英語不是我的主要語言。 – Ruud 2012-07-25 15:22:38
嗨,你可以發佈一個使用模式字符串中的兩個raw_inputs(年份,數字)的例子嗎? 我搜索的例子,但無法找到或得到任何工作。我需要re.compile/re.group部分嗎? – Ruud 2012-07-26 15:01:20
@Ruud,'re.compile'只是讓正則表達式運行得更快。如果你爲大數目(> 1000?)做了這個,那麼你可以嘗試使用re.compile作爲模式。我會先運行它,如果它看起來很慢,你可以嘗試優化。 're.group'只顯示比賽的不同部分 - 在這種情況下,你只關心你的整個模式匹配。我剛剛修改我的第一個示例,使用'raw_input'來獲取年份/編號。 – 2012-07-27 13:11:39