Python - 如何接受和遍历多个文件?使用agrv

Python - How to Accept and Loop Over Multiple Files? Using 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 行,文件 test.txt 的信息 (a-c) 和 sample.txt 的 3 行 (a-c)。

我不知道的是: - 如何使用 argv 在命令行中接受 1 个或多个文件? - 如何遍历那些打开的文件,分别读取和显示每个文件的输出?

下面我有一个初步的例子,但是一次只能取1个文件。它基于我在 Learn Python the Hard Way 中找到的内容。

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)

你可以这样做。希望这可以让您大致了解如何解决该问题。

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('*******-------*******')

请注意,这适用于包含多个单词的单行文件。如果有多行,请注意脚本中包含的注释。