Меню

Object of type io textiowrapper has no len ошибка

I keep getting the error when running my code:

TypeError: object of type ‘_io.TextIOWrapper’ has no len() function

How do I get it to open/read the file and run it through the loop?

Here’s a link to the file that I am trying to import:
download link of the DNA sequence

    def mostCommonSubstring():
        dna = open("dna.txt", "r")
        mink = 4
        maxk = 9
        count = 0
        check = 0
        answer = ""
        k = mink
        while k <= maxk:
            for i in range(len(dna)-k+1):
                sub = dna[i:i+k]
                count = 0
                for i in range(len(dna)-k+1):
                    if dna[i:i+k] == sub:
                        count = count + 1
                if count >= check:
                    answer = sub
                    check = count
            k=k+1
        print(answer)
        print(check)

ktdrv's user avatar

ktdrv

3,5223 gold badges29 silver badges45 bronze badges

asked Feb 9, 2018 at 23:45

Anonymous's user avatar

2

The problem occurs due to the way you are opening the text file.
You should add dna = dna.read() to your code.
so your end code should look something like this:

def mostCommonSubstring():
    dna = open("dna.txt", "r")
    dna = dna.read()
    mink = 4
    maxk = 9
    count = 0
    check = 0
    answer = ""
    k = mink
    while k <= maxk:
        for i in range(len(dna)-k+1):
            sub = dna[i:i+k]
            count = 0
            for i in range(len(dna)-k+1):
                if dna[i:i+k] == sub:
                    count = count + 1
            if count >= check:
                answer = sub
                check = count
        k=k+1
    print(answer)
    print(check)

answered Feb 9, 2018 at 23:51

Nazim Kerimbekov's user avatar

Nazim KerimbekovNazim Kerimbekov

4,6668 gold badges33 silver badges58 bronze badges

0

@tfabiant : I suggest this script to read and process a DNA sequence.
To run this code, in the terminal: python readfasta.py fastafile.fasta

import string, sys
##########I. To Load Fasta File##############
file = open(sys.argv[1]) 
rfile = file.readline()
seqs = {} 
##########II. To Make fasta dictionary####
tnv = ""#temporal name value
while rfile != "":
    if ">" in rfile:
        tnv = string.strip(rfile)
        seqs[tnv] = ""
    else:
        seqs[tnv] += string.strip(rfile)    
    rfile = file.readline()
##############III. To Make Counts########
count_what = ["A", "T", "C", "G", "ATG"]
for s in seqs:
    name = s
    seq = seqs[s]
    print s # to print seq name if you have a multifasta file
    for cw in count_what:
        print cw, seq.count(cw)# to print counts by seq

answered Feb 22, 2018 at 0:59

Fabian Tobar-Tosse's user avatar

The complete code is as follows:

from Crypto.Protocol.KDF import scrypt
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes

class transmitter():

    def __init__(self):

        self.random_password = None
        self.message_plain = True
        self.key = None
        self.salt = None

        self.password_option()
        self.text_option()
        self.encrypt()


    def password_option(self):

        while ( self.random_password == None ):

            random = input("nDo you want to generate a random symmetric key? (y/n)nn>>> ").strip().lower()

            if random == "y":
                self.random_password = True
                self.random()

            elif random == "n":
                self.random_password = False
                self.random()

            else:
                pass

    def text_option(self):

        if self.message_plain:

            question = input("nHow will you enter your message?nn[1] filenn[2] directly in the programnn>>> ").strip()

            if question == "1":
                path = input("nEnter the file pathnn>>> ")
                name = path.split("\")[-1]
                with open(name,mode = "r") as self.message_plain:
                    self.message_plain.read().encode("utf-8")

            elif question == "2":
                self.message_plain = input("nEnter your messagenn>>> ").strip()
                self.message_plain = self.message_plain.encode("utf-8")


    def random(self):

        if self.random_password:
            password = "password".encode("utf-8")
            self.salt = get_random_bytes(16)
            self.key = scrypt(password, self.salt, 16, N=2**14, r=8, p=1)

        else:
            password = input("nEnter your passwordnn>>> ").strip()
            self.salt = get_random_bytes(16)
            self.key = scrypt(password.encode("utf-8"), self.salt, 16, N=2**14, r=8, p=1)


    def encrypt(self):

        cipher = AES.new(self.key,AES.MODE_GCM)
        cipher.update(b"header")
        cipher_text,tag_mac = cipher.encrypt_and_digest(self.message_plain)
        transmitted_message = cipher_text,tag_mac,self.salt,cipher.nonce
        Receptor(transmitted_message)

class receiver():

    def __init__(self,received_message):
        # nonce = aes_cipher.nonce
        self.cipher_text,self.tag_mac,self.salt,self.nonce = received_message
        self.decrypt(self.cipher_text,self.tag_mac,self.salt,self.nonce)

    def decrypt(self,cipher_text,tag_mac,salt,nonce):

        try:
            password = input("nEnter your passwordnn>>> ").strip()
            decryption_key = scrypt(password.encode("utf-8"), salt, 16, N=2**14, r=8, p=1)
            cipher = AES.new(decryption_key,AES.MODE_GCM,nonce)
            cipher.update(b"header")
            plain_text = cipher.decrypt_and_verify(cipher_text,tag_mac)
            plain_text = plain_text.decode("utf-8")
            print(f"nText -> {plain_text}n")

        except ValueError:
            print("nAn error has occurred..n")

if __name__ == '__main__':
    init = transmitter()

And the error is as follows:

Traceback (most recent call last):
  File ".crypto.py", line 109, in <module>
    init = Emisor()
  File ".crypto.py", line 16, in __init__
    self.encrypt()
  File ".crypto.py", line 74, in encrypt
    cipher_text,tag_mac = cipher.encrypt_and_digest(self.message_plain)
  File "C:UsersEQUIPOAppDataLocalProgramsPythonPython37-32libsite-packagesCryptoCipher_mode_gcm.py", line 547, in encryp
t_and_digest
    return self.encrypt(plaintext, output=output), self.digest()
  File "C:UsersEQUIPOAppDataLocalProgramsPythonPython37-32libsite-packagesCryptoCipher_mode_gcm.py", line 374, in encryp
t
    ciphertext = self._cipher.encrypt(plaintext, output=output)
  File "C:UsersEQUIPOAppDataLocalProgramsPythonPython37-32libsite-packagesCryptoCipher_mode_ctr.py", line 189, in encryp
t
    ciphertext = create_string_buffer(len(plaintext))
TypeError: object of type '_io.TextIOWrapper' has no len()

I have tried everything but honestly, I don’t know what else to do.
Does anyone know what could be wrong?

Basically, what I want to do is save the result of reading a certain file in a variable. So that I can encrypt it. Fortunately, the rest of the code is doing well, only that one block of code (the first one I put in the question) that presents the error.

I’m trying to organize a dataset that I downloaded. Currently, I have a directory of images and an Excel spreadsheets with values for those images. I’m trying to combine those into a single dataframe that has one column for image filename and another for the actual file. Here’s the code I have currently:

for filename in os.listdir("C:\Users\arnav\Dataset\Images"):
    new_filename = filename
    if(filename[0] == '.'):
        new_filename = filename[2:]
    picture = open(new_filename)
    filename_file.loc[filename_file['Filename'] == new_filename,'File'] = picture

The filename_file dataframe has 5500 rows with 2 columns, one for filename and one for the file. I managed to load the filenames in, so right now it has all zeros for the File column. When I run the loop I get this error:

Traceback (most recent call last):
  File "data.py", line 16, in <module>
    filename_file.loc[filename_file['Filename'] == new_filename,'File'] = picture
  File "C:UsersarnavAnaconda3libsite-packagespandascoreindexing.py", line 190, in __setitem__
    self._setitem_with_indexer(indexer, value)
  File "C:UsersarnavAnaconda3libsite-packagespandascoreindexing.py", line 604, in _setitem_with_indexer
    elif can_do_equal_len():
  File "C:UsersarnavAnaconda3libsite-packagespandascoreindexing.py", line 554, in can_do_equal_len
    values_len = len(value)
TypeError: object of type '_io.TextIOWrapper' has no len()

I don’t know why this is happening, can anyone help?

Буквально самый простой способ исправить NullReferenceExeption имеет два пути. Если у вас есть GameObject, например, с прикрепленным скриптом и переменной с именем rb (rigidbody), эта переменная начнет пустую, когда вы начнете игру. Вот почему вы получаете NullReferenceExeption, потому что на компьютере нет данных, хранящихся в этой переменной.

В качестве примера я буду использовать переменную RigidBody. Мы можем добавить данные действительно легко на самом деле несколькими способами:

  1. Добавить RigidBody к вашему объекту с помощью AddComponent> Физика> Rigidbody Затем зайдите в свой скрипт и введите rb = GetComponent<Rigidbody>();. Эта строка кода работает лучше всего под ваши функции Start() или Awake().
  2. Вы можете добавить компонент программно и назначить переменную одновременно с одной строкой кода: rb = AddComponent<RigidBody>();

Дальнейшие заметки: если вы хотите, чтобы единство добавлялось компонент для вашего объекта, и вы, возможно, забыли добавить его, вы можете ввести [RequireComponent(typeof(RigidBody))] над объявлением класса (пробел ниже всех ваших приложений). Наслаждайтесь и получайте удовольствие от игр!

задан Shane 22 August 2010 в 06:23

поделиться

9 ответов

Не встроен, но алгоритм R(3.4.2) («Резервуарный алгоритм Уотермана») из «Искусство компьютерного программирования» Кнута хорош (в очень упрощенной версии):

import random

def random_line(afile):
    line = next(afile)
    for num, aline in enumerate(afile):
      if random.randrange(num + 2): continue
      line = aline
    return line

num + 2 создает последовательность 2, 3, 4 … Таким образом, randrange будет 0 с вероятностью 1.0/(num + 2) — и это вероятность, с которой мы должны заменить выбранную в данный момент линию (особый случай размер выборки 1 ссылочного алгоритма — см. книгу Кнута для доказательства корректности ==, и, конечно же, мы также имеем дело с достаточно маленьким «резервуаром» для размещения в памяти; -) … и точно вероятность с которым мы делаем так.

ответ дан Alex Martelli 27 August 2018 в 05:52

поделиться

Это зависит от того, что вы подразумеваете под «слишком большими» накладными расходами. Если сохранить весь файл в памяти, возможно, что-то вроде

import random

random_lines = random.choice(open("file").readlines())

выполнит трюк.

ответ дан cji 27 August 2018 в 05:52

поделиться

Вы можете добавить строки в набор (), который будет произвольно изменять их порядок.

filename=open("lines.txt",'r')
f=set(filename.readlines())
filename.close()

Чтобы найти 1-ю строку:

print(next(iter(f)))

Чтобы найти 3-й line:

print(list(f)[2])

Чтобы перечислить все строки в наборе:

for line in f:
    print(line)

ответ дан GoTrained 27 August 2018 в 05:52

поделиться

import random

with open("file.txt", "r") as f:
    lines = f.readlines()
    print (random.choice(lines))

ответ дан HCLivess 27 August 2018 в 05:52

поделиться

Если вы не хотите читать весь файл, вы можете искать его в середине файла, затем искать назад для новой строки и вызывать readline.

Вот Python3 скрипт, который делает именно это,

. Одним из недостатков этого метода является то, что короткие линии имеют более низкое вероятность появления.

def read_random_line(f, chunk_size=16):
    import os
    import random
    with open(f, 'rb') as f_handle:
        f_handle.seek(0, os.SEEK_END)
        size = f_handle.tell()
        i = random.randint(0, size)
        while True:
            i -= chunk_size
            if i < 0:
                chunk_size += i
                i = 0
            f_handle.seek(i, os.SEEK_SET)
            chunk = f_handle.read(chunk_size)
            i_newline = chunk.rfind(b'n')
            if i_newline != -1:
                i += i_newline + 1
                break
            if i == 0:
                break
        f_handle.seek(i, os.SEEK_SET)
        return f_handle.readline()

ответ дан ideasman42 27 August 2018 в 05:52

поделиться

Ищите случайную позицию, читайте строку и отбрасывайте ее, затем читайте другую строку. Распределение линий не будет нормальным, но это не всегда имеет значение.

ответ дан Ignacio Vazquez-Abrams 27 August 2018 в 05:52

поделиться

Хотя я опаздываю на четыре года, я думаю, что у меня есть самое быстрое решение. Недавно я написал пакет python под названием linereader , который позволяет вам манипулировать указателями дескрипторов файлов.

Вот простое решение для получения случайной строки с этим пакетом:

from random import randint
from linereader import dopen

length = #lines in file
filename = #directory of file

file = dopen(filename)
random_line = file.getline(randint(1, length))

В первый раз это делается хуже всего, так как linereader должен скомпилировать выходной файл в специальном формате. После этого linereader может получить доступ к любой строке из файла быстро, независимо от размера файла.

Если ваш файл очень маленький (достаточно маленький, чтобы вписаться в MB), вы можете заменить dopen с copen, и он делает кэшированную запись файла в памяти. Это происходит не только быстрее, но вы получаете количество строк в файле, поскольку оно загружается в память; это делается для вас. Все, что вам нужно сделать, это создать случайный номер строки. Вот пример кода для этого.

from random import randint
from linereader import copen

file = copen(filename)
lines = file.count('n')
random_line = file.getline(randint(1, lines))

Я просто очень рад, потому что увидел кого-то, кто мог бы воспользоваться моим пакетом! Извините за мертвый ответ, но пакет определенно может быть применен ко многим другим проблемам.

ответ дан Nick Pandolfi 27 August 2018 в 05:52

поделиться

Это может быть громоздким, но это работает, я думаю? (по крайней мере, для txt-файлов)

import random
choicefile=open("yourfile.txt","r")
linelist=[]
for line in choicefile:
    linelist.append(line)
choice=random.choice(linelist)
print(choice)

Он считывает каждую строку файла и добавляет его в список. Затем он выбирает случайную строку из списка. Если вы хотите удалить строку после ее выбора, просто сделайте

linelist.remove(choice)

. Надеюсь, что это может помочь, но, по крайней мере, никаких дополнительных модулей и импорта (кроме случайных) и относительно легкого.

ответ дан Philip Hughes 27 August 2018 в 05:52

поделиться

import random
lines = open('file.txt').read().splitlines()
myline =random.choice(lines)
print(myline)

Для очень длинного файла: найдите случайное место в файле на основе его длины и найдите два символа новой строки после позиции (или новой строки и конца файла). Повторите 100 символов до или с начала файла, если исходная позиция поиска была & lt; 100, если мы оказались внутри последней строки.

Однако это сложнее, так как файл является итератором. возьмите random.choice (если вам нужно много, используйте random.sample):

import random
print(random.choice(list(open('file.txt'))))

ответ дан Tony Veijalainen 27 August 2018 в 05:52

поделиться

Другие вопросы по тегам:

Похожие вопросы:

The python error TypeError: object of type ‘type’ has no len() occurs while attempting to find the length of an object that returns ‘type’. The python variables can store object data types. If a python variable refers a data type, it can’t be used in length function. The Length function is used for data structures that store multiple objects. The data type of the variable that store another data type is called ‘type’.

For example list is a data type, list() returns a object of type list. int is a data type, where as int() returns int value. Python supports to store a data type and value in a variable.

a = int   -- stores data type
a = int() -- stores a int value

The python variables can store the data types and classes. These variables are not assigned any value, or objects. The length function can not be called the variables which are not allocated with any value or object. If you call the length function for these variables of ‘type’, it will throw the error TypeError: object of type ‘type’ has no len()

The basic data types are int, float, long, bool, complex etc. Some of the collections types are list, tuple, set, dict etc. Python allows to store these data types in a variable. The data type of the variable that store another data type is called ‘type’.

Exception

The error TypeError: object of type ‘type’ has no len() will show the stack trace as below

Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 2, in <module>
    print len(s)
TypeError: object of type 'type' has no len()
[Finished in 0.1s with exit code 1]

How to reproduce this issue

If a python variable is assigned with a data type, the type of the variable would have ‘type’. If the length function is invoked for the ‘type’ variable, the error TypeError: object of type ‘type’ has no len() will be thrown.

s=list
print len(s)

Output

Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 2, in <module>
    print len(s)
TypeError: object of type 'type' has no len()
[Finished in 0.1s with exit code 1]

Root Cause

The python variables are used to store any object or value. The values of the primitive data type such as int, float, long, boot etc can be stored in any python variable. Python is an object oriented programming language. The objects can be stored in Python variables. As the python variables are not declared with any data types, python can support to store a python function and a data type.

If a data type (not a value or object) is stored with a python variable, the length function can not be used for such variable. So, the error TypeError: object of type ‘type’ has no len() is thrown

Solution 1

The python variable which is assigned with a data type, should be assigned with a value or object. If the variable is not assigned with any value or object , assign with an object such as list, tuple, set, dictionary etc.

list – is a data type, where as list() is an object of type list

s=list()
print len(s)

Output

0
[Finished in 0.1s]

Solution 2

Due to the dynamic creation of the variable the python variable may not assigned with data types. The datatype of the variable is ‘type’. In this case, the data type must be checked before the length function is called.

s=list
print type(s)
if s is list : 
	print "Value is type"
else:
	print (len(s))

Output

<type 'type'>
Value is type
[Finished in 0.0s]

Solution 3

The python variable should be validated for the data type. The length function is used to find the number of items in the objects. Before calling the length function, the object must be validated for the collection of items.

s=list
print type(s)
if type(s) in (list,tuple,dict, str): 
	print (len(s))
else:
	print "not a list"

Output

<type 'type'>
not a list
[Finished in 0.1s]

Solution 4

The try and except block is used to capture the unusual run time errors. If the python variable contains expected value, then it will execute in the try block. If the python variable contains the unexpected value, then the except block will handle the error.

s=type
print s
try :
	print (len(s))
except :
	print "Not a list"

Output

<type 'type'>
Not a list
[Finished in 0.0s]

Я парсю этот ресурс.Беру заголовок,дату и контент новости.

Выходит следующие сообщение об ошибке:

 Traceback (most recent call last):
  File "C:/Users/Администратор/PycharmProjects/Task/parser.py", line 130, in <module>
    call_all_func(resources)
  File "C:/Users/Администратор/PycharmProjects/Task/parser.py", line 112, in call_all_func
    item_title = get_item_title(item_page,title_rule)
  File "C:/Users/Администратор/PycharmProjects/Task/parser.py", line 35, in get_item_title
    soup = BeautifulSoup(item_page, 'lxml')
  File "C:UsersАдминистраторAppDataLocalProgramsPythonPython37-32libsite-packagesbs4__init__.py", line 267, in __init__
    elif len(markup) <= 256 and (
TypeError: object of type 'NoneType' has no len()
Process finished with exit code 1

Как я понял из ошибки,ошибка содержится в этом участке кода:

 # < Собираем заголовки с страницы.
def get_item_title(item_page,title_rule):
    soup = BeautifulSoup(item_page, 'lxml')
    item_title = soup.find(title_rule[0],{title_rule[1]:title_rule[2]})
    print(item_title)
    return item_title['content']

В title_rule=meta , title_rule=property , title_rule=og:title

Я решил сделать print(item_title) На выводе:

 vesti
кол-во ссылок: 34
http://vesti.kz//khl/269571/
<meta content='Прямая трансляция первого матча "Барыса" в новом сезоне КХЛ' property="og:title"/>
http://vesti.kz//profi/269572/
<meta content='"Я вернусь в Украину чемпионом мира". Деревянченко сделал очередное заявление перед боем с Головкиным' property="og:title"/>
http://vesti.kz//mirfutbol/269569/
<meta content="Криштиану Роналду составил завещание" property="og:title"/>
http://vesti.kz//wta/269568/
<meta content="Путинцева показала лучший результат в карьере и завершила выступление на US Open " property="og:title"/>
http://vesti.kz//mirfutbol/269566/
<meta content="Месси получил приз фонда Папы Римского " property="og:title"/>
http://vesti.kz//amateur/269565/
<meta content="Казахстанский боксер рассказал о подготовке к ЧМ и включил Узбекистан в число главных соперников" property="og:title"/>
http://vesti.kz//national/269564/
<meta content="Сборная Казахстана начала подготовку к матчам с Кипром и Россией в отборе на Евро-2020" property="og:title"/>
http://vesti.kz//sportsout/269563/
<meta content="Китайский миллиардер из рейтинга Forbes передал Головкину эстафету в челлендже" property="og:title"/>
http://vesti.kz//uefa/269509/
<meta content='Кто из звезд "Манчестер Юнайтед" может приехать в Казахстан на матч с "Астаной" в Лиге Европы' property="og:title"/>
http://vesti.kz//france/269562/
<meta content="ПСЖ подписал трехкратного победителя Лиги чемпионов и отдал в аренду чемпиона мира" property="og:title"/>
http://vesti.kz//amateur/269561/
<meta content="Василий Левит оценил свою форму и озвучил задачу на ЧМ-2019 по боксу " property="og:title"/>
http://vesti.kz//mirfutbol/269560/
<meta content="ФИФА назвала трех претендентов на награду лучшему футболисту года" property="og:title"/>
http://vesti.kz//profi/269547/
Traceback (most recent call last):
  File "C:/Users/Администратор/PycharmProjects/Task/parser.py", line 130, in <module>
    call_all_func(resources)
  File "C:/Users/Администратор/PycharmProjects/Task/parser.py", line 112, in call_all_func
    item_title = get_item_title(item_page,title_rule)
  File "C:/Users/Администратор/PycharmProjects/Task/parser.py", line 35, in get_item_title
    soup = BeautifulSoup(item_page, 'lxml')
  File "C:UsersАдминистраторAppDataLocalProgramsPythonPython37-32libsite-packagesbs4__init__.py", line 267, in __init__
    elif len(markup) <= 256 and (
TypeError: object of type 'NoneType' has no len()
Process finished with exit code 1

После вывода (если я правильно понял) код ругается на эту ссылку.

Как решить эту ошибку? По ошибке мне понятно только

что объект типа ‘NoneType’ не имеет len ()

Отредактировано r4khic (Сен. 3, 2019 08:16:03)

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Object not found kaspersky ошибка обновления
  • Odin ошибка md5 error binary is invalid