繁体   English   中英

如何使用此代码在Python 3中解析另外两个文件?

[英]How can I use this code to parse two more files in 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')
# 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循环中的函数中以使其更干净,但这是为该任务使用循环的一般思路。

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM