Как убрать ошибку в скрипте ?

satfan

Пользователь
Пользователь
Апр 21, 2020
98
6
8
Win 10
IDLE (Python 3.10 64-bit)
-----------------------------
Есть такой скрипт:
Python:
# -*- coding: utf-8 -*-
import sys, time, urllib.request, urllib.parse, urllib.error;

t = '*****************************************************'
x = '* (C) 2015 - 2018 Aleksey S.Galickiy for ProxyTV RU *'
t = '*****************************************************'

tvg_autor = '"https://www.youtube.com/channel/UCQGGNWAIMrlmfMZN-oO3fPQ"'

def NewPlist(fileName, delay):
    print()
    count = 0
    total = 0
    http = 'http://'
    extInf = '#EXTINF:-1'
    
    try:
        openList = open(fileName+'.m3u', 'r', encoding='utf-8')
        for line in openList.readlines():
            if line.find(extInf) != -1: count += 1
            if count == 1 and line.find(http) != -1:
                try:
                    udpx = line.split('/')
                    urllib.socket.setdefaulttimeout(delay)
                    stream = urllib.request.urlopen('%s%s' % (http, udpx[2]))
                    print('UDPXY >>> %s <<< GooD\n' % udpx[2])
                except:
                    print('UDPXY >>> %s <<< BaD\n' % udpx[2])
                    print("Bye, bye people.")
                    time.sleep(5)
                    sys.exit()
        print('Count channel:', str(count))
        openList.close()
        
    except Exception as error:
        print("Error: %s\n" % error)
        print("Bye, bye people.")
        time.sleep(3)
        sys.exit()

    count = 0
    openList = open(fileName+'.m3u', 'r')
    openNewList = open('new_%s.m3u' % fileName, 'w')
    openNewList.write('#EXTM3U tvg-autor="%s"\n\n' % tvg_autor)
    
    for line in openList.readlines():
        if line.find(extInf) != -1:
            extName = line.split(',')
            newLine = '%s,%s' % (extInf, extName[1])

        if line.find(http) != -1:
            count += 1
            ln = line.rstrip('\t\r\n')
            try:
                urllib.socket.setdefaulttimeout(delay)
                stream = urllib.request.urlopen(line)
                data = stream.read(8192)
                if len(data) == 8192:
                    print('channel #%s >>> GooD' % count)
                    openNewList.write(newLine)           
                    openNewList.write(line)
                    newLine = ""
                    total += 1
                else:
                    print('channel #%s >>> NoT' % count)
            except:
                print('channel #%s >>> BaD' % count)
                
    print('Total channel: %s' % total)

print('%s\n%s\n%s\n\n' % (t, x, t))   
filename = input("Input file name: ")

try:
    delay = float(input("Delay input(sec): "))
    if delay < 3: delay = 3
except:
    delay = 3
    
NewPlist(filename, delay)
print("Bye, bye people.")
#time.sleep(3)
try:
    filename = input("OK?")
except:
    pass
Выдаёт ошибку:
Input file name: _5
Delay input(sec): 3

Count channel: 89
Traceback (most recent call last):
File "C:\Users\Пк\Desktop\verifyPlaylist\_verifyPlaylist.py", line 80, in <module>
NewPlist(filename, delay)
File "C:\Users\Пк\Desktop\verifyPlaylist\_verifyPlaylist.py", line 46, in NewPlist
for line in openList.readlines():
File "C:\Python\lib\encodings\cp1251.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x98 in position 2493: character maps to <undefined>
Как её исправить ?
 

stud_55

Модератор
Команда форума
Модератор
Апр 3, 2020
1 522
672
113
UnicodeDecodeError: 'charmap' codec can't decode byte 0x98 in position 2493: character maps to <undefined>
Как её исправить ?
Попробуйте указать кодировку при открытии файлов.
Замените эти строки:
Python:
openList = open(fileName+'.m3u', 'r')
openNewList = open('new_%s.m3u' % fileName, 'w')
на такие
Python:
openList = open(fileName+'.m3u', 'r', encoding='utf-8')
openNewList = open('new_%s.m3u' % fileName, 'w', encoding='utf-8')
 

satfan

Пользователь
Пользователь
Апр 21, 2020
98
6
8
Спасибо.
Заменил. Теперь другая ошибка:
C:\Python\python.exe "E:/__Мои скрипты/1_test/_verifyPlaylist.py"
File "E:\__Мои скрипты\1_test\_verifyPlaylist.py", line 47
for line in openList.readlines('encoding='utf-8'):
^
SyntaxError: expected ':'

Process finished with exit code 1
 

stud_55

Модератор
Команда форума
Модератор
Апр 3, 2020
1 522
672
113
Вы видимо не там заменили.
Эту строку менять не нужно
Python:
for line in openList.readlines():
нужно заменить
Python:
openList = open(fileName+'.m3u', 'r')
openNewList = open('new_%s.m3u' % fileName, 'w')
на
Python:
openList = open(fileName+'.m3u', 'r', encoding='utf-8')
openNewList = open('new_%s.m3u' % fileName, 'w', encoding='utf-8')
 

satfan

Пользователь
Пользователь
Апр 21, 2020
98
6
8
Спасибо stud_55
Теперь всё Ок.
Удачи.
 

Форум IT Специалистов