0

I am reading a file line by line and let's say I don't care about anything except "if" this line of the file contains an upper case letter. Because if it does I want to use it. I don't want to use the this line of the file if it does not.

Could I use just an if statement for this? or do I have to use a for loop. I already have two nested statements.

My code:

with open(var) as config_file: #open file
for line in config_file: #line by line reading of file
    #if "description" and capital letter is contain in line:
        line = line.replace('\n' , '').replace('"' , '').replace(']' , '') #removes all extra characters
        i = "| except " + (line.split("description ", 1)[1]) + " " #split the line and save last index (cust name)
        cus_str+=i #append to string
config_file.close()

3 Answers3

5

Yes. The built-in any function makes this simple:

with open(filename) as f:
    for line in f:
        if any(letter.isupper() for letter in line):
            print(line)
Patrick Haugh
  • 49,982
  • 11
  • 66
  • 73
  • To add on to Patrick's answer, you could also have used `if any(letter in string.ascii_uppercase for letter in line):`, assuming the `string` module has been imported and you're more comfortable with that. – Joel Jul 13 '18 at 17:21
  • Thank you so much! follow up question because I have some strange cases. After the substring "description_" of the line, if the next *letter* found after that is uppercase...print this line. How would I do that? – Camille Burke Jul 13 '18 at 17:36
  • That's probably easiest to express as a regular expression `re.search(r"description_[A-Z]", line)` – Patrick Haugh Jul 13 '18 at 17:38
1

A regular expression is probably overkill for this, but it's extremely simple:

import re
if re.search('[A-Z]', line):
Mark Ransom
  • 271,357
  • 39
  • 345
  • 578
-1
with open(var) as config_file :
    data = [i.strip() for i in config_file.readlines() if any(j != j.lower() for j in i)]

data will contain only strings with uppercase characters.

lenik
  • 21,662
  • 4
  • 29
  • 38