[Solved] Trying to read all lines in a file and pick out the ones that begin with ‘H’ or ‘S’ [closed]


So, first thing you need to do is open the file so that you can see what’s in it. Here is the documentation for that, with examples.

Make sure that you can see it line by line inside of a for loop by using the print function:

for line in file:
   print(line)

Now that you can see each line, one at a time, you can split it based on a space and take the last value:

name = line.split()[-1]

print the value again to make sure you’re getting what you expect.

Now that you have each name, you can check to see if it starts with your desired letter:

if name[0] in "SH":
    print(name)

If it does, store it in a list (rather than print it as above) and then use the file documentation link I posted to start with to see how to write back out to a file.

Here is a full example to get you going:

inFile = open(r"\path\to\names.txt", 'r')

required = "HS"
valid = []

for line in inFile:
    name = line.split()[-1]

    if name[0].upper() in required:
        valid.append(line)

outFile = open(r"\path\to\validNames.txt", 'w')

for line in valid:
    outFile.write(line)

3

solved Trying to read all lines in a file and pick out the ones that begin with ‘H’ or ‘S’ [closed]