使用索引更改日志文件

时间:2015-02-22 12:12:49

标签: python string list file python-2.7

我有一个包含用户的文件:

Sep 15 04:34:31 li146-252 sshd[13326]: Failed password for invalid user ronda from 212.58.111.170 port 42579 ssh2

尝试使用string的索引方法来编辑文件中的用户。到目前为止,我能够打印用户,但现在要删除并输入新用户。

newuser = 'PeterB'
with open ('test.txt') as file: 
        for line in file.readlines(): 
                lines = line.split() 
                string = ' '.join(lines)
                print string.index('user')+1

2 个答案:

答案 0 :(得分:1)

您要更新文件内容吗?如果是这样,您可以更新用户名,但您需要重写该文件,或写入第二个文件(为安全起见):

keyword = 'user'
newuser = 'PeterB'
with open('test.txt') as infile, open('updated.txt', 'w') as outfile:
    for line in infile.readlines():
        words = line.split()
        try:
            index = words.index(keyword) + 1
            words[index] = newuser
            outfile.write('{}\n'.format(' '.join(words)))
        except (ValueError, IndexError):
            outfile.write(line)    # no keyword, or keyword at end of line

请注意,此代码假定输出文件中的每个单词都由一个空格分隔。

另请注意,此代码不会删除不包含关键字的行(与其他解决方案一样)。


如果要保留原始空格,正则表达式非常方便,结果代码相对简单:

import re

keyword = 'user'
newuser = 'PeterB'
pattern = re.compile(r'({}\s+)(\S+)'.format(keyword))

with open('test.txt') as infile, open('updated.txt', 'w') as outfile:
    for line in infile:
        outfile.write(pattern.sub(r'\1{}'.format(newuser), line))

答案 1 :(得分:0)

如果您想更改日志中的名称,请按以下步骤操作。

file = open('tmp.txt', 'r')
new_file = []
for line in file.readlines():  # read the lines
    line = (line.split(' '))
    line[10] = 'vader'  # edit the name
    new_file.append(' '.join(line))  # store the changes to a variable

file = open('tmp.txt', 'w')  # write the new log to file
[file.writelines(line) for line in new_file]