繁体   English   中英

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

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

我正在读取一个文件并基于以下代码的分隔符写入一个新文件

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)

如果输入文件包含一个 \\n ,它会被添加到 data.txt 但是当我尝试读取它时 \\n 值在它是最后一行时没有得到反映

1,2
2,3

3,4

如果我理解你的问题,那么做

lines = f.readlines()[-1]

然后您将能够阅读最后一行。

暂无
暂无

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

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