讀取檔案 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
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')
執行結果如下:
原始檔:
目標檔案:
Python 去除檔案中的空行
def clear space with open test r encoding utf 8 as fr for line in fr line line.strip if len line 0 yield line g clear space for line in g with open te...
python 基礎 3 2 檔案 for 練習
usr bin python coding utf 8 time 2017 11 1 22 19 auther liuzhenchuan file 1030 1031練習題.py 1 把乙個數字的list從小到大排序,然後寫到檔案中,然後從檔案中讀取檔案內容然後反序,在追加到檔案的 下一行中 2 分...
2019 05 16 檔案練習
encoding utf 8 判斷 乙個檔案中有幾行含英文單詞 def jedgeword row 0 with open c users huhuili desktop python a.txt r encoding utf8 as fp contents fp.readlines for lin...