2016-03-22 8 views
0

Ich versuche, ein Programm zu erstellen, das mehrere Dateien nimmt und die Informationen unten für jede Datei einzeln anzeigt.Python - Wie man mehrere Dateien akzeptiert und durchläuft? Mit 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 

Fügen Sie zum Beispiel, wenn zwei Dateien auf der Kommandozeile: test.txt und sample.txt => die Ausgabe 3 Zeilen mit der info (ac) für Datei test.txt sein wird und 3 Zeilen (ac) für sample.txt.

Was ich nicht weiß ist: - Wie akzeptiert man 1 oder mehr Dateien in der Befehlszeile mit Argv? - Wie man über diese Dateien Schleife so geöffnet, lesen und die Ausgabe individuell für jede Datei anzeigen?

Ich habe ein vorläufiges Beispiel unten, aber es kann nur 1 Datei auf einmal nehmen. Es basiert auf dem, was ich in Lerne Python auf dem harten Weg gefunden habe.

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

'Skript, Dateinamen = argv [0], argv [1:]' kann tun, was Sie wollen. – Evert

+0

Wenn Sie jedoch nach einer Schleife suchen und die 'for'-Anweisung verwenden möchten, sollten Sie weitere Python-Lernprogramme lesen. – Evert

Antwort

2

Sie können so etwas tun. Hoffentlich kann dies Ihnen eine allgemeine Vorstellung davon geben, wie Sie das Problem angehen können.

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

Seien Sie vorsichtig, dass dies für eine einzelne Zeile Datei mit mehreren Wörtern funktioniert. Wenn Sie mehrere Zeilen haben, achten Sie auf die Kommentare im Skript.

+0

Vielen Dank! Das half mir zu verstehen, was ich in meinem Code vermisst hatte. Ich habe einige Änderungen vorgenommen und jetzt funktioniert es. – brazjul