将行更新到文件后附加Python

时间:2015-08-06 17:50:16

标签: python python-2.7

我有一个包含内容的文字文件:

pb333u$Paul Barron   $20001:24001:26001:28001$30001:34001:36001:38001$40001:44001:46001:48001::

pk7319$Patrick Val      $20002:24002:26002:28002$30002:34002:36002:38002$40002:44002:46002:48002::

pb348u$Victor Ataler$20003:24003:26003:28003$30003:34003:36003:38003$40003:44003:46003:48003::

我想要的是在文件中添加另一行,例如:

th3674$Tom Harry$20004:24004:26004:28004$30004:34004:36004:38004$40004:44004:46004:48004::

基本上,有一个新的id和名字;并且每个数字加1。

我写了这个python程序来实现上述目的:

def parse_file1():
   id_dict = {'at_id':'th3674','full_name':'Tom Harry'}
   f=open('ports.dat','a+')
   lines = f.readlines()
   if lines:
       last = lines[-1]
       last = last.replace(last.split('$')[0],id_dict['at_id'])
       last = last.replace(last.split('$')[1],id_dict['full_name'])
       split_colon(last)
       f.write('\n')
       f.write(last)

def split_colon(line):
    for i in range(2,5): 
        key = line.split('$')[i]
        for j in range(4):
            v = key.split(':')[j]
            line = line.replace(v, str(int(v) + 00001))

if __name__=='__main__':
    parse_file1()

我得到的输出是:

pb333u$Paul Barron   $20001:24001:26001:28001$30001:34001:36001:38001$40001:44001:46001:48001::

pk7319$Patrick Val      $20002:24002:26002:28002$30002:34002:36002:38002$40002:44002:46002:48002::

pb348u$Victor Ataler$20003:24003:26003:28003$30003:34003:36003:38003$40003:44003:46003:48003::

th3674$Tom Harry$20003:24003:26003:28003$30003:34003:36003:38003$40003:44003:46003:48003::

我无法将最后一行中的数字增加1.另外,有没有更好的方法来实现上述目标?我觉得我的程序有点太不通用了。

1 个答案:

答案 0 :(得分:3)

问题是字符串是不可变的,而在你的split_colon()函数中,当你这样做时 -

line = line.replace(v, str(int(v) + 00001))

这不会更改last函数中的实际parse_file1()字符串。您需要将更改后的line返回,并将其设置回last变量,然后再将其写入文件。示例 -

def parse_file1():
   id_dict = {'at_id':'th3674','full_name':'Tom Harry'}
   f=open('ports.dat','a+')
   lines = f.readlines()
   if lines:
       last = lines[-1]
       last = last.replace(last.split('$')[0],id_dict['at_id'])
       last = last.replace(last.split('$')[1],id_dict['full_name'])
       last = split_colon(last)
       f.write('\n')
       f.write(last)

def split_colon(line):
    for i in range(2,5): 
        key = line.split('$')[i]
        for j in range(4):
            v = key.split(':')[j]
            line = line.replace(v, str(int(v) + 1))
    return line

if __name__=='__main__':
    parse_file1()

此外,只需向其中添加1,无需将数字定义为 - 00001(在Python 2.x中,当您使用0开始数字时,它将变为八进制文字,尽管这不会影响你的程序。)