Python入门:文件内容去重操作

# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#   学习是一种态度,只要你有态度,学习将会是一种乐趣
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# python3.5
'''
1、对特定文件内容进行去重操作
2、请输入需要去重文件的绝对路径
3、删除文件中的空行
4、去除字符串前后空行
5、生成一个以当前日期命名的文件
'''

import time

year = time.localtime().tm_year
mon = time.localtime().tm_mon
day = time.localtime().tm_mday
hour = time.localtime().tm_hour
min = time.localtime().tm_min
sec = time.localtime().tm_sec
nowtime = str(year) + str(mon) + str(day) + str(hour) + str(min) + str(sec)

f = input("please entry the file[absolute path]:")


def openThefile():
    '''
    1、打开要去重的文件
    2、删除每行数据前后的无用字符
    :return:
    '''
    ff = open(f, 'r')
    l = []
    # for i in ff.readline():     #readline是文件中的第一行内容
    for i in ff.readlines():  # 所有内容中的每一行
        ii = i.replace('\t', '').strip()
        l.append(ii)
    ff.close()
    return l


def createNewfile(openThefile):
    '''
    去重操作
    :param openThefile:
    :return:
    '''
    l = []
    for i in openThefile:
        if i not in l:
            l.append(i)
    '''
    创建新文件
    '''
    filename = f[:f.find('.')]
    postfix = f[f.find('.'):]
    theNewfile = open(filename + nowtime + postfix, 'a')
    '''
    写入处理过的内容
    '''
    for i in l:
        theNewfile.writelines(i + '\n')
    theNewfile.close()


if __name__ == '__main__':
    createNewfile(openThefile())

== == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == ==

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值