简体   繁体   中英

How to only print lines from a file containing a certain string?

I have some code here that takes data from a file and asks the user what location they want to see data for.

def main():
    #ask user for a city or county and store that as a variable
    location = input("Please enter a location. Make sure to add County if the location is a county ")
    location = location.capitalize()

    print("=== Data for",location," ===")
    print("Date  Total Cases  Hospitalizations  Deaths")

    #open the file
    covidFile = open("Covid Data.txt", "r")

    #read the first line to move it aside from the rest of the data
    firstLine = covidFile.readline()

    #read the rest of the data in the file using a for loop
    for dataLine in covidFile:

        #strip the data line
        dataLine = dataLine.rstrip("\n")

        #split the line into a dataList
        dataList = dataLine.split(",")

        #if location matches dataList[2]
        if location in dataList:
            date = str(dataList[0])
            cases = int(dataList[4])
            hospitalizations = int(dataList[5])
            deaths = int(dataList[6])
            print(date,"  ",cases,"  ",hospitalizations,"  ",deaths)

        #if location does not match dataList[2]
        else:
            print("No data was found for that city or county.")

    #close file
    covidFile.close()

However, there's a problem where the code will print out long strings of "No data was found for that city or county", followed by a line of code from the file. I'm trying to figure out how I fix the code so that it only prints out data for the location that the user types in (if the location is in the file, of course).

I an bad at english so I can mis understood your question

lines = file.open(*.txt)
lines = lines.readlines()
list = []
for x in lines:
    if str in x:
        list.append(x)

Have you tried entirely removing the else statement? I mean you only need to print out whenever the location is found.

If you still need to print something when nothing is found you could create a boolean, lets say data_found = False and mark it as True if you ever enter the if statement. Then at the very end of the script after closing the file you check if not data_found and there you print your "No data was found for that city or county."

Just use a variable to store if the data is found:

found = False
for dataline in Covidfile:
    if condition:
        .
        .
        .
        found = True
if not found:
    print("No data was found for that city or county.")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM