得到txt空白行的行數、將txt檔案的空行刪除和刪除csv檔案中指定的行

花開 流年發表於2020-10-09

得到txt空白行的行數

blankline = []
def tong1(filename):
    with open(filename, 'r') as f:
        num = 0
        for line in f:
            num += 1
            if len(line) == 1:
                blankline.append(num)
              #  print(num)  
        print('%s' % num)
file1 = 'train-ops.txt'
value = num = 0
tong1(file1)
print(blankline)
print(len(blankline))
blankline = []
def tong1(filename):
    with open(filename, 'r') as f:
        num = 0
        for line in f:
            num += 1
            if len(line) == 1:
                blankline.append(num)
              #  print(num)  
        print('%s' % num)
file1 = 'train-ops.txt'
value = num = 0
tong1(file1)
print(blankline)
print(len(blankline))
#將blankline列表裡的每一個元素減1
aftersub = [i-1 for i in blankline]
print(aftersub)

在這裡插入圖片描述

將txt檔案的空行刪除

with open("train-ops.txt","r",encoding="utf-8") as f:
    lines = f.readlines()
    #print(lines)
with open("del-train-ops.txt","w",encoding="utf-8") as f_w:
    for line in lines:
        if len(line) ==1 :
            continue
        f_w.writelines(line)

在這裡插入圖片描述
刪除csv檔案中指定的行
import pandas as pd
csv_data = pd.read_csv(‘train-length.csv’)
cc = csv_data.drop([18, 9850, 10714]
)
cc.to_csv(‘deleteafterlength.csv’)

相關文章