2017-09-20 20 views
0

到目前爲止,我編寫了下面的程序來搜索一個文件。我還有兩個我想要搜索的文件。我相信功能應該能夠做到這一點,但我不知道從哪裏開始。如何讓它在每個文件名上運行代碼而不是複製整個代碼並替換相關文本?如何使用此代碼解析Python 3中的另外兩個文件?

# declares the files used 
gameslist = 'gameslist.txt' 
name1 = 'filename1' # I wrote the code for this one 
# I want to change the code to do the next two files without repeating 
# it and changing the names, as that is inefficient. 
name2 = 'filename2' 
name3 = 'filename3' 

# imports the necessary libraries 
import os, time 
from stat import * # ST_SIZE etc 

# finds the time the file was last modified and prints it 
try: 
    st = os.stat(name1) 
except IOError: 
    print("failed to get information about", name1) 
else: 
    print("At:", time.asctime(time.localtime(st[ST_MTIME]))) 

# checks the file for the string 'Minecraft' 
if 'Minecraft' in open(name1).read(): 
    print('name1 was playing Minecraft') 

# checks the file for the string 'LoL' 
if 'LoL' in open(name1).read(): 
    print('name1 was playing LoL') 
+0

有點失落。在try/except塊中,當在name1上調用try塊時,爲什麼要打印(「failed ...」,name2)? –

+0

那是一個type-o。我在那裏有女兒的名字,並且把它改爲name1,並且必須打錯了鍵。 – Stefany

回答

0
# declares the files used 
gameslist = 'gameslist.txt' 
filenames = ['filename1','filename2' ,'filename3'] 


for filename in filenames: 
    # imports the necessary libraries 
    import os, time 
    from stat import * # ST_SIZE etc 

    # finds the time the file was last modified and prints it 
    try: 
     st = os.stat(filename) 
    except IOError: 
     print("failed to get information about", filename) 
    else: 
     print("At:", time.asctime(time.localtime(st[ST_MTIME]))) 

    with open(filename, 'r') as f: 
     file_content = f.read() 

    # checks the file for the string 'Minecraft' 
    if 'Minecraft' in file_content: 
     print('{} was playing Minecraft'.format(filename)) 

    # checks the file for the string 'LoL' 
    if 'LoL' in file_content: 
     print('{} was playing LoL'.format(filename)) 

你可以把東西放在for循環的功能,使之更乾淨,但這是使用循環此任務的總體思路。

0
def search_in_file(string, file_name): 
    current_file = open(file_name) 
    if string in current_file.read(): 
     print('name1 was playing %s' % string) 
    current_file.close() 

這裏是你將如何使用它:這裏

search_in_file('Minecraft', name1) 
search_in_file('LoL', name1) 
+1

爲不存在的文件添加錯誤捕獲,這在這裏很容易就是最好的答案。 –

+0

在行中:print('name1正在播放%s'%string),不會每次打印「name1」嗎? – Stefany

+0

嗯,是的。 如果您願意,您還可以將「name1」作爲變量。 –