Django学习笔记(三十六):Django读取文件内容,并进行操作后,再写入文本

#先将所需操作的文件放置再static目录下的一个子目录下
_change_status_root = os.path.join(STATIC_ROOT,'player_status')
#mkdirs()是创建多级目录
mkdirs(_change_status_root)
#用于写入错误信息的error.txt
error_file_path = os.path.join(_change_status_root,'error.txt')
#用于读取所需操作信息的player.txt
push_file_path = os.path.join(_change_status_root,'player.txt')


@Route(r'^log/change_neibuhao_status$')
@notauth
def change_neibuhao_status(request):
    '''
    :param request: 批量修改内部号玩家状态
    :return: 返回操作结果
    '''
    error_ls = []
    try:
        #读取player.txt文件
        with open(push_file_path , 'r') as pfp:
            #循环读取每一行的数据
            for line in pfp.readlines():
                #获取所需操作玩家的信息
                player_neibu = int(line.replace('\n', ''))
                server_neibu = player_neibu >> 20
                print player_neibu, server_neibu
                #连接数据库修改所需操作玩家的状态
                conn = Server.get_conn(server_neibu)
                cur = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)
                sql = '''UPDATE player_%s SET user_type  = 1 WHERE player_id  = %d ''' % (
                    server_neibu, player_neibu)
                cur.execute(sql)
                conn.close()
            with open(error_file_path, 'w') as efp:
                for v in error_ls:
                    efp.write('%s\n' % v)
                    efp.flush()
                    efp.close()
    except Exception as e:
        print e
    return HttpResponse('success')

 

你可能感兴趣的:(Django)