Python2.7从文本文件读取最后一个空行

2024-09-29 21:25:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在读一个文件,并根据下面代码的分隔符写入一个新文件

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


Tags: 文件forreaddataifaswithopen

热门问题