删除文件中的空白行

时间:2018-08-03 02:12:24

标签: python python-3.x io

我看过多个问题帖子,我想知道如何摆脱文件的最后一行,或者说是空白行

infile = open("milkin.txt","r").readlines()   
outfile = open("milkout.txt","w")                                                           

number = infile[0]                            
arrayLoc = infile[1].split( )                 
array = infile[2].split( )                                                                  

dictionary = {}                                                                             

for i, z in zip(arrayLoc, array):             
    dictionary[i] = z                         

for key in sorted(dictionary):                
    outfile.write(dictionary[key])            
    outfile.write("\n")                       

outfile:
5520059
8089172
7180540
6513926
9202362
2641421
2897763
2383426
1490027
1368690

数字下方有多余的一行,我想将其删除

4 个答案:

答案 0 :(得分:2)

您可以将str.join与生成器表达式一起使用,以避免尾随换行符:

更改:

for key in sorted(dictionary):                
    outfile.write(dictionary[key])            
    outfile.write("\n")

收件人:

outfile.write('\n'.join(dictionary[key] for key in sorted(dictionary)))

答案 1 :(得分:1)

错误在这里:

outfile.write("\n") 

这应该做:

newline = ''
for key in sorted(dictionary):
    outfile.write(newline)
    outfile.write(dictionary[key])
    newline = '\n'

由于newline被初始化为空字符串,因此文件开头不会有空行。

答案 2 :(得分:0)

这是@jsub答案的改进版本:

for line, key in enumerate(sorted(dictionary)):   
    if line: # Do not do for line #0!
        outfile.write("\n")               
    outfile.write(dictionary[key])

答案 3 :(得分:0)

OR:

infile = open("milkin.txt","r").readlines()   
outfile = open("milkout.txt","w")                                                           

number = infile[0]                            
arrayLoc = infile[1].split( )                 
array = infile[2].split( )                                                                  

dictionary = {}                                                                             

for i, z in zip(arrayLoc, array):             
    dictionary[i] = z                         

for key in sorted(dictionary):                
    outfile.write(dictionary[key])            
    outfile.write("\n")
outfile.writelines([dictionary[key] if list(sorted(dictionary))[-1]==key else dictionary[key]+'\n' for idx,key in enumerate(sorted(dictionary))])