0

How can I rewrite the below code using only single if condition instead of two if conditions in Python 3.7?

with open('demo.csv', 'r') as f, open("Result_csv.csv", 'w+') as out:
    for line in f:
        if '/tcp' in line:
            print(line)
            out.write(line)
        if '/udp' in line:
            print(line)
            out.write(line)
iz_
  • 15,923
  • 3
  • 25
  • 40
Gali Ashok
  • 21
  • 3

2 Answers2

5
with open('demo.csv', 'r') as f, open("Result_csv.csv", 'w+') as out:
    for line in f:
        if '/tcp' in line or '/udp' in line:
            print(line)
            out.write(line)
NemoMeMeliorEst
  • 513
  • 4
  • 10
1

You could also use regular expression to search multiple substrings.

import re
with open('demo.csv', 'r') as f, open("Result_csv.csv", 'w+') as out:
    for line in f:
        if re.search('/tcp|/udp', line):
            print(line)
            out.write(line)
Venkatachalam
  • 16,288
  • 9
  • 49
  • 77