python练习:1.文件去除空行和注释

读取文件 cdays−4-test.txt 内容,去除空行和注释行后,以行为单位进行排序,并将
结果输出为 cdays−4-result.txt。

  1 #!/usr/local/bin/python3
  2 #-*- coding = utf-8 -*-
  3 import os
  4 import sys
  5 
  6 oldfile = open("cdays-4-test.txt", "r") #以只读方式打开要求的文件
  7 
  8 if os.path.exists("cdays-4-test.txt") == False: #判断该文件是否存在
  9 >---print('no this file named cdays-4-test.txt')		
 10      return
 11 newfile = open("cdays-4-result.txt", "w")
 12 
 13 if os.path.exists("cdays-4-result.txt"):
 14 >---print('this file has been creat,are you sure to change it?')
 15 >---print('If you don \'t want that ,hit CTRL-C')
 16 >---print('If you do want that, hit RETURN')
 17 
 18 input("?")    #询问是否继续
 19 
 20 newfile.truncate()   # 继续的话就清空该文件,这条命令慎用
 21 result = list()
 22 while True:
 23 >---readbuff = oldfile.readline()
 24 >---if readbuff == "":   #判断是否读到文件末尾, readline 空行还有\n
 25 >--->---break
 26 >---
 27 >---if readbuff == '\n' or readbuff.startswith('#'):    #判断是否为空行或者注释行
 28 >--->---continue
 29 >---result.append(readbuff.strip("\n"))     #去除每一行的\n,因为readline是把\n转成了字符串
 30 
 31 result.sort()    #字符串排序
 32 #print(type(result))
 33 for x in result:     
 34 >---newfile.write(str(x))  
 35 >---newfile.write('\n')        #写入时加换行符,尽量保持源文件的格式
 36 
 37 oldfile.close()
 38 newfile.close()
 39 
 40 print('cdays-4-result.txt has been created and changed')

运行结果如下:
在这里插入图片描述
源文件:
在这里插入图片描述
目标文件:
在这里插入图片描述

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值