0

I'm trying to write a piece of code that will take certain values in a string and output them. The problem is the dataset I'm working with isn't perfect and there are many parts where the data is empty. I'm looking for a way to get python to ignore the blank values and just continue onwards

rfile = open("1.txt", "r", encoding= "utf8") combos = rfile.readlines() a=0 nfile = open("2.txt ", "w+") numx = 0 for line in combos: x = combos[a] y=(x.split('Points = ')) z= int(y[-1]) numx += 1 print (z) print (numx) rfile.close() nfile.close() exi = input("Press any key to close") 

Example of the dataset would be like:

Person 1 | Points = 22 Person 2 | Points = <--- This is the problematic data Person 3 | Points = 15 

Any help would be greatly appreciated!

7
  • Just to clarify, I want python to check whether z is empty, and if it is to just ignore it. Commented Jun 21, 2020 at 20:09
  • 1
    if z: should work. Commented Jun 21, 2020 at 20:10
  • You can just check if y[-1] is the empty string "". Commented Jun 21, 2020 at 20:10
  • Does this answer your question? python: how to check if a line is an empty line Commented Jun 21, 2020 at 20:11
  • z= y[-1] != ''? int(y[-1]) : '' Commented Jun 21, 2020 at 20:12

2 Answers 2

1

You can check if variable is empty string, or just None, thy something like: if not value: continue

Sign up to request clarification or add additional context in comments.

Comments

0

After

 y = (x.split('Points = ')) 

If it is guaranteed that the lines with missing data only have a single space after the =, e.g. 'Person 2 | Points = ' so that y[-1] == '', you can simply do the following to skip over this one and carry on (goes to the start of the next iteration of the for loop):

 if not y: continue 

relying on the fact that an empty string counts as a false value.

If it might contain additional whitespace, then you will have to deal with this. There are various options:

  1. test the characters of the string one by one
 for c in y[-1]: # looping over the characters in y[-1] if c != ' ': # if a non-space character is found break # then break from this inner "for" loop else: # but if this loop completed without break continue # then start next iteration of the outer "for" loop 
  1. use a regular expression parser (needs import re at the top)
 if re.match('\s*$', y[-1]): continue 
  1. just try to convert it to int anyway, and catch the exception if it fails:
 try: z = int(y[-1]) except ValueError: continue 

(All of these will still work if the string is indeed empty.)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.