检查空行并将其移除/移动它下面的行

时间:2016-05-04 21:32:24

标签: python list file

我一直在寻找解决我现有问题的方法,但无济于事。

我有以下功能:

def showEmail():
    f = open("players.txt","r") 
    for line in f:
        lineList = line.split(";") 
        print "Name: " + lineList[0] + " " + lineList[1]
        print "Email address: " + lineList[2]
        print ""
    f.close()

我的文件包含如下文字:

Sam;Tyler;s.tyler@gmail.com;0710503687;6;0
Peter;Bond;p.bond@gmail.com;0798415758;6;0
Joe;Blogg;j.bloggs@gmail.com;0749814574;1;60

当我的文件中不可避免地出现空行时出现问题(当修改一行时,程序将创建一个类似于修改过的行的新行并更改该行的值。然后删除原始行,并复制新的,即空行,并将其全部复制到新文档中)。这如图所示完成。 :

def writeToFile(): #function to write all new (modified) lines from players to a temps file, deletes players and rename temps to 'players'
    f = open("players.txt",'r') # Input file
    t = open("temp.txt", 'w') #Temp output file

    for line in f:
        if line != originalInfo: #doesn't write the line that is the same as the original info
            t.write(line) #writes all lines apart from the original line (one that needs to be deleted)

    f.close()
    t.close()
    os.remove("players.txt") #deletes players
    os.rename('temp.txt', 'players.txt') #new file with modified info is renamed to players

如果文件包含以下内容,程序将告诉我列表索引超出范围,这是有道理的,因为它将空行视为列表。

Sam;Tyler;s.tyler@gmail.com;0710503687;6;0
Peter;Bond;p.bond@gmail.com;0798415758;6;0

Joe;Blogg;j.bloggs@gmail.com;0749814574;1;60

我该如何解决这个问题?谢谢!

3 个答案:

答案 0 :(得分:1)

如果您已修改并可能清除了一行,则应在编写之前检查该行是否为空:

def writeToFile():
    ...
    for line in f:
        if line != originalInfo and line != "\n" # or whatever you're using for an empty line
             t.write(line)
    ...

答案 1 :(得分:0)

您的文件格式化为CSV文件,那么使用Python提供的csv模块怎么样,请看下面的例子:

import csv

def showEmail():
    with open("player.txt","r") as f:
        csvFile = csv.reader(f, delimiter=';')
        for line in csvFile:
            if line:
                print("Name: {} {}".format(line[0], line[1]))
                print("Email address: {}".format(line[2]))
                print("")

答案 2 :(得分:0)

我更喜欢这个:

with open(file) as f_in:
    return filter(None, (line.rstrip() for line in f_in))