【问题标题】:What should I do to exclude my program from reading empty lines in text files but still include spaces我应该怎么做才能排除我的程序读取文本文件中的空行但仍然包含空格
【发布时间】:2020-10-06 18:56:25
【问题描述】:
#read the data from the file
#takes in file name
def readFile(fileName):
    myFile=open(fileName,"r")
    #reading the lines in the file and returning the data skips the first line
    fileData=myFile.readlines()[1:]
    myFile.close()
    myNewList = []
    numRow = 0
    numCol = 0
    emptyLines = 0
    #from 0 to the length of the file data list
    for i in range(0,len(fileData),1):
        #creating a empty list for each row of data if the line is not empty
        if fileData[i].strip() != "":
            myNewList.append([])
        #checks for empty lines
        if fileData[i].strip() == "":
            emptyLines = emptyLines + 1 
        numRow = numRow + 1
        #if file data at a certain index with no spaces dosen't equal a empty line
        if fileData[i].strip() != NEWLINE:
            #removing spaces and splitting data by spaces
            myElements=fileData[i].strip().split(SPACE)
            myElements=fileData[i].split()
            for j in range(0,len(myElements),1):
                numCol = len(myElements)
                if myElements[j].strip() != SPACE:
                    myNewList[i].append(int(myElements[j]))
#calculating and displaying the total
def display(myList,numRow,numCol):
    total = 0

    #loops 7 times for just the first 7 numbers but in every row
    for i in range(0,numRow,1):
        total = 0
        for j in range(0,numCol,1):
            if j < 7:
                if myList[i][j] != "":
                    print("%s" %myList[i][j], end = "-")
                    total = total + myList[i][j]
        print("Total=%s"%total)

我需要做些什么来排除没有空格的空行被添加到二维数组中。如果文本文件底部有空行但中间没有空行,我有办法将它们排除在外。我基本上希望程序不包含空行

【问题讨论】:

    标签: python arrays file


    【解决方案1】:

    改成

    fileData=myFile.readlines()[1:]
    

    这个

    fileData = [line.strip() for line in myFile.readlines()[1:] if line.strip()]
    

    遍历文件的每一行并使用if line.strip() 检查空行,如果它是空行,它将返回False。如果它没有将该行添加到列表中fileData。

    使用 for 循环:

    fileData = []
    for line in fp.readlines()[1:]:
        if line.strip():
            fileData.append(line.strip())
    

    【讨论】:

    • 你能解释一下这是怎么回事吗?
    • 如果您愿意,我可以简化您的代码,只需在您的文件中分享数据样本
    • 如何更改此语句以包含包含空格的空行
    • 它只会删除空行它不会删除空格
    • 但是如果我的行只有空格怎么办
    猜你喜欢
    • 2018-12-30
    • 2012-02-06
    • 1970-01-01
    • 2011-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-20
    相关资源
    最近更新 更多