2016-03-22 11 views
0

Birden çok dosya alacak ve her bir dosya için ayrı ayrı bilgileri görüntüleyen bir program oluşturmaya çalışıyorum. ÖrneğinPython - Birden Fazla Dosya Nasıl Kabul Edilir ve Dönebilir? Agrv kullanarak

#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 

, komut satırında iki dosya eklerseniz: sınama.txt ve örnek.txt => çıktı dosyası test.txt için bilgi (AC) ile 3 satır olacak ve Sample.txt için 3 satır (ac).

Bilmiyorum: - Argv kullanarak komut satırında 1 veya daha fazla dosya nasıl kabul edilir? - Bu dosyalar nasıl açılır, böylece her dosya için çıktıyı ayrı ayrı okuyun, okuyun ve görüntüleyin?

Aşağıda bir ön örnek var, ancak her seferinde yalnızca 1 dosya alabilir. Learn Python Hard Way'de bulduğum şeyi temel alıyor.

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:]' istediğini yapabilir. – Evert

+0

Eğer 'for' ifadesini kullanmayı ve kullanmayı düşünüyorsanız, daha fazla Python öğreticisi okumak isteyebilirsiniz. – Evert

cevap

2

Böyle bir şey yapabilirsiniz. Umarım bu, probleme nasıl yaklaşacağınıza dair genel bir fikir verebilir.

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

Bunun, birden çok sözcük içeren tek satırlı bir dosya için çalıştığından emin olun. Birden çok satıra sahipseniz, komut dosyasında yer alan yorumlara dikkat edin.

+0

Teşekkürler! Bu, kodumdan neleri kaçırdığımı anlamama yardımcı oldu. Bazı değişiklikler yaptım ve şimdi çalışıyor. – brazjul

İlgili konular