Python - 如果它是换行符,则删除最后一行

时间:2018-05-22 02:15:38

标签: python

我的目标是检查文件并查看最后一行是否为换行符(空),如果是,则将其删除。我已经尝试了很多像这样的方法等等:

for filename in os.listdir(directory):
    if filename.endswith(".ADC"):
        with open(os.path.join(directory, filename)) as infile, open(os.path.join(directory, filename)) as outfile:
            lines = infile.readlines()
        if lines:
            lines[-1] = lines[-1].rstrip('\r\n')
            infile.writelines(lines)

也尝试了readlines方法但没有成功。

2 个答案:

答案 0 :(得分:0)

检查最后一行是否为空字符串。如果是,则计算前面行的总大小,然后将文件截断为该大小。

for filename in os.listdir(directory):
    if filename.endswith(".ADC"):
        with open(os.path.join(directory, filename), "r") as file:
            lines = file.readlines()
            if lines and lines[-1].rstrip('\r\n') == "":
                lines.pop()
                size = sum(len(l) for l in lines)
                file.truncate(size)

截断比没有最后一行重写整个文件更有效。

答案 1 :(得分:0)

试试这个:

for filename in os.listdir(directory):
    if filename.endswith(".ADC"):
        with open(os.path.join(directory, filename), "r") as f:
            lines = f.readlines()
            for line in lines[::-1]:
                if line == '\n' or line == '\r':
                    lines = lines[:-1]
            print(lines)