使用python计算文件中删除行数的最佳方法



我想知道使用python计算文件中删除行数的最简单方法是什么。它是取前后行的索引并减去吗?或者有没有一种方法可以计算循环中删除的行数?

在下面的示例文件中,我有一个before用户输入文件和一个after文件,用于从用户输入中排除任何包含负数或空格的行。我意识到我要么需要计算前后文件,要么想办法计算note_consider[]列表中的项目。

import os, sys
inFile = sys.argv[1]
baseN = os.path.basename(inFile)
outFile = 'c:/example.txt'
#if path exists, read and write file
if os.path.exists(inFile):
inf = open(inFile,'r')
outf = open(outFile,'w')
#reading and writing header
header = inf.readline()
outf.write(header)
not_consider = []
lines = inf.read().splitlines()
for i in range(0,len(lines)):
data = lines[i].split("t")
for j in range(0,len(data)):
if (data[j] == '' or float(data[j]) < 0):
#if line is having blank or negtive value
# append i value to the not_consider list
not_consider.append(i)
for i in range(0,len(lines)):
#if i is in not_consider list, don't write to out file
if i not in not_consider:
outf.write(lines[i])
print(lines[i])
outf.write("n")   
inf.close()
outf.close()

此代码读取输入中的文件,并在输出文件中写入非空或非数字的行。这是你所期望的吗?

如果不使用有关not_considered行的信息,则可以删除关联的代码,并将for line_idx, line in enumerate(ifile.readlines()):替换为for line in ifile.readlines():

with open(<filename>, <mode>) as file:语句负责在该语句的作用域中打开和关闭文件。

def is_number(line: str):
try:
float(line)
return True
except ValueError:
return False

with open("./file.txt", "r") as ifile, open("output.txt", "w") as ofile:
not_considered = []
for line_idx, line in enumerate(ifile.readlines()):
if line == "n" or is_number(line):
not_considered.append(line_idx)
continue
ofile.write(line)
print(f"not considered  : {not_considered}")
print(f"n not considered: {len(not_considered)}")

输入文件:

this is
1234
a
file
with a lot
42
of empty lines

输出文件:

this is
a
file
with a lot
of empty lines

控制台输出:

not considered  : [1, 2, 3, 5, 7, 9, 10]
n not considered: 7

相关内容

最新更新