到目前爲止,我編寫了下面的程序來搜索一個文件。我還有兩個我想要搜索的文件。我相信功能應該能夠做到這一點,但我不知道從哪裏開始。如何讓它在每個文件名上運行代碼而不是複製整個代碼並替換相關文本?如何使用此代碼解析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')
有點失落。在try/except塊中,當在name1上調用try塊時,爲什麼要打印(「failed ...」,name2)? –
那是一個type-o。我在那裏有女兒的名字,並且把它改爲name1,並且必須打錯了鍵。 – Stefany