2016-03-22 52 views
0

我試圖創建一個程序,將採取多個文件,並單獨爲每個文件顯示下面的信息。Python - 如何接受和循環多個文件?使用agrv

#a) The name of the file 
#b) The total number of words in the file, 
#c) The first word in the file and the length 

例如,如果在命令行上添加兩個文件:的test.txtsample.txt的 =>的輸出將是3行與信息(AC),用於文件test.txt和sample.txt的3行(ac)。

我不知道的是: - 如何使用argv在命令行中接受1個或多個文件? - 如何循環打開這些文件,讀取並顯示每個文件的輸出文件?

我在下面有一個初步的例子,但它一次只能取1個文件。這是基於我在學習Python困難之路中找到的。

from sys import argv 

script, filename = argv 

print "YOUR FILE NAME IS: %r" % (filename) 

step1 = open(filename) 
step2 = step1.read() 
step3 = step2.split() 
step4 = len(step3) 

print 'THE TOTAL NUMBER OF WORDS IN THE FILE: %d' % step4 

find1 = open(filename) 
find2 = find1.read() 
find3 = find2.split()[1] 
find4 = len(find3) 

print 'THE FIRST WORD AND THE LENGTH: %s %d' % (find3 , find4) 
+0

'script,filenames = argv [0],argv [1:]'可以做你想做的事。 – Evert

+0

如果您正在尋找如何循環並使用'for'語句,您可能需要閱讀更多的Python教程。 – Evert

回答

2

你可以這樣做。希望這可以給你一個關於如何解決這個問題的總體思路。

from sys import argv 

script, filenames = argv[0], argv[1:] 

# looping through files 
for file in filenames: 
    print('You opened file: {0}'.format(file)) 
    with open(file) as f: 
     words = [line.split() for line in f] # create a list of the words in the file 
     # note the above line will create a list of list since only one line exists, 
     # you can edit/change accordingly 
     print('There are {0} words'.format(len(words[0]))) # obtain length of list 
     print('The first word is "{0}" and it is of length "{1}"'.format(words[0][0], 
                     len(words[0][0]))) 
     # the above line provides the information, the first [0] is for the first 
     # set in the list (loop for multiple lines), the second [0] extract the first word 
    print('*******-------*******') 

只是要謹慎,這適用於單詞文件與多個單詞。如果您有多行,請注意腳本中包含的註釋。

+0

謝謝!這幫助我瞭解了我從代碼中遺漏了什麼。我做了一些修改,現在它工作。 – brazjul

相關問題