Что мне делать, чтобы моя программа не читала пустые строки в текстовых файлах, но по-прежнему включала пробелы - PullRequest
1 голос
/ 17 июня 2020
#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)

что мне нужно сделать, чтобы исключить добавление пустых строк без пробелов в массив 2d. У меня был способ исключить их, если в нижней части текстового файла есть пустые строки, но не в середине. Я в основном хочу, чтобы программа не включала пустые строки

1 Ответ

1 голос
/ 17 июня 2020

Измените это на

fileData=myFile.readlines()[1:]

this

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

Цикл по каждой строке файла и проверка пустых строк с помощью if line.strip(), он вернет False, если это пустая строка. если он не добавляет эту строку в список fileData.

Использование для l oop:

fileData = []
for line in fp.readlines()[1:]:
    if line.strip():
        fileData.append(line.strip())
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...