首页 > python文件操作

python文件操作

def generate_tpl_file(*tpl_ids, file_name='FCIDEA.2016051016.txt'):
    with open(file_name, 'r', encoding='utf8') as bao_wen_file:
        for tpl_id in tpl_ids:
            id_str = str(tpl_id)
            out_file_name = id_str + '.txt'
            with open(out_file_name, 'w', encoding='utf8') as file:
                for line in bao_wen_file:
                    line_list = line.strip('\n').split('\3')
                    try:
                        if str(tpl_id) in line_list:
                            index = line_list.index(id_str)
                            info = '#'.join(line_list[index - 1:index][0].split('\6'))
                            file.write(info)
                            file.write('\n')
                    except:
                        continue
                        

希望大家可以帮忙看下,为什么我用generate_tpl_file(23,24,25)这个形式来调用函数,只会生成一个文件23.txt,不是很理解啊?我本来预想应该是生成23.txt,24.txt,25.txt三个文件才对啊,本人是python菜鸟,本来以为是with的问题,可是换成file = open()也是一个结果,希望各位大神可以帮忙看看,谢谢!

def generate_tpl_file(tpl_id, file_name='FCIDEA.2016051016.txt'):
    with open(file_name, 'r', encoding='utf8') as bao_wen_file:
        id_str = str(tpl_id)
        out_file_name = id_str + '.txt'
        with open(out_file_name, 'w', encoding='utf8') as file:
            for line in bao_wen_file:
                line_list = line.strip('\n').split('\3')
                try:
                    if str(tpl_id) in line_list:
                        index = line_list.index(id_str)
                        info = '#'.join(line_list[index - 1:index][0].split('\6'))
                        file.write(info)
                        file.write('\n')
                except:
                    continue
                    
                    

第二个是另一个版本的函数,分别调用三次generate_tpl_file(23),generate_tpl_file(24),
generate_tpl_file(25)则可以正常生成3个文件


运行了你的脚本,正常阿。。


你应该传入list,而不是tuple
tpl_ids = [23,24,25]
generate_tpl_file(tpl_ids, file_name='FCIDEA.2016051016.txt')


generate_tpl_file([1,2,3])

def generate_tpl_file(tpl_ids, file_name='FCIDEA.2016051016.txt'):
    with open(file_name, 'r', encoding='utf8') as bao_wen_file:
        for tpl_id in tpl_ids:
            id_str = str(tpl_id)
            out_file_name = id_str + '.txt'
            with open(out_file_name, 'w', encoding='utf8') as file:
                for line in bao_wen_file:
                    line_list = line.strip('\n').split('\3')
                    try:
                        if str(tpl_id) in line_list:
                            index = line_list.index(id_str)
                            info = '#'.join(line_list[index - 1:index][0].split('\6'))
                            file.write(info)
                            file.write('\n')
                    except:
                        continue
【热门文章】
【热门文章】