简体   繁体   English

python 2.7 从文本文件中读取最后一个空行

[英]python 2.7 reading a last empty line from a text file

I am reading a file and writing to a new file based on a seperator with below code我正在读取一个文件并基于以下代码的分隔符写入一个新文件

dataFile = sys.argv[1]
def fileread(inputfile):
    with open(inputfile,'r') as f:
        lines = f.readlines()
 for line in lines:
        print "Inside for"
        print line
def read_master_file(dataFile):
    try:
        with open(dataFile) as fmaster:
            op=''
            start=0
            for seperator in fmaster.read().split('\n'):
                #print x
                if(seperator=="####"):
                    if(start == 1):
                        with open("data.txt",'w') as fdata:
                            #print op
                            fdata.seek(0,2)
                            fdata.write(op)
                            fdata.close()
                            fileread("data.txt")
                            #sys.exit(1)
                            op=''
                    else:
                        start = 1
                else:
                    if (op ==''):
                        op = seperator
                    else:
                        op = op + '\n' + seperator
        fmaster.close()
    except Exception as e:
        print "File not found", e
read_master_file(dataFile)

If the input file contains a \\n , it is getting added in data.txt but when i try reading it the \\n value is not getting reflected when it is a last line如果输入文件包含一个 \\n ,它会被添加到 data.txt 但是当我尝试读取它时 \\n 值在它是最后一行时没有得到反映

1,2
2,3

3,4

If I am understanding your question then do如果我理解你的问题,那么做

lines = f.readlines()[-1]

And then you will be able to read last line.然后您将能够阅读最后一行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM