2016-03-22 31 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

相关问题