0

I need to write a program having a GUI to input a File - shtech1.txt Then need to open the file and extract lines between

  • show vlan

and

  • show

and write to another file - shvlan1.txt

Below is my program and I am getting error TypeError: can't use a string pattern on a bytes-like object on the line:

if re.match('- show vlan -',line):

Could someone help me on this

Code:

def on_pushButton_clicked(self): #shtech1
    dialog = QFileDialog(self)
    dialog.exec_()
    for file in dialog.selectedFiles():
        shtech1 = QFile(file)
        shtech1.open(QFile.ReadOnly)
        found = False
        copy = False
        shvlan1 = open('shvlan1.txt', 'a')
        while not found:
           line = shtech1.readLine()
           print("line is",line)

           if re.match('- show vlan -',line):
              copy = True
              print ("copy is True")
           elif re.match('- show',line):
              if copy:
                 found = True
                 copy = False
                 print ("copy is False")
              elif copy:
                 shvlan1.write(line)
                 print ("printing")
    shvlan1.close()
    shtech1.close()

Getting the below error:

File "UImlag.py", line 34, in on_pushButton_clicked
if re.match('- show vlan -',line):
File "/usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/re.py", line 160, in match
return _compile(pattern, flags).match(string)
TypeError: can't use a string pattern on a bytes-like object
Fabio Antunes
  • 22,251
  • 15
  • 81
  • 96
AjazV.A
  • 3
  • 2

2 Answers2

0

Use

str(line).decode('utf-8')

to turn it into a string that regex handles. You may need to replace with the encoding used by your qt (which is a preference).

mdurant
  • 27,272
  • 5
  • 45
  • 74
0

You need to be careful when mixing Qt and Python APIs when working with files.

Here's what happens when you read a line using QFile:

>>> from PyQt5 import QtCore
>>> qfile = QtCore.QFile('test.txt')
>>> qfile.open(QtCore.QFile.ReadOnly)
True
>>> qfile.readLine()
PyQt5.QtCore.QByteArray(b'foo\n')

So, in Python, it's just like opening a file like this:

>>> pfile = open('test.txt', 'rb')
>>> pfile.readline()
b'foo\n'

only you end up with a QByteArray instead of bytes.

The Qt way to open files in text-mode is to use a QTextStream:

>>> stream = QtCore.QTextStream(qfile)
>>> stream.readLine()
'foo\n'

But really, why mess around like that when you can just do this:

>>> pfile = open('test.txt')
>>> pfile.readline()
'foo\n'

(Just because you are getting a filename from a QFileDialog doesn't mean you have to use the Qt APIs to read from it.)

ekhumoro
  • 115,249
  • 20
  • 229
  • 336