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,6123 gold badges30 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,6928 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

Hey, i’ve got a list inside a file like [«one», «two», «three»], which i’d like to import into my python script. I’ve tried it with
list1 = open(«list1.txt», «r») but that didn’t work. Could somebody help me with this please? I’m new to python and i just need to fix this one last problem.

This is the whole script.

import random, time, tweepy

list1 = open("list1.txt", "r")
list2 = open("list2.txt", "r")
list3 = open("list3.txt", "r")

def one():
    return random.choice(list1) + random.choice(list2)

def two():
    return random.choice(list2) + random.choice(list3)

#I'm working on a Twitter bot, that's just some twitter stuff down here 
consumer_key = 'XXX'
consumer_secret = 'XXX'
access_token = 'XXX'
access_token_secret = 'XXX'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

while True:
    postthis = random.choice([one,two])()
    if len(postthis) <= 140:
        api.update_status(status=postthis)
        time.sleep(10)

And the error message:

Traceback (most recent call last):
  File "C:/Users/User/Desktop/Example/example.py", line 22, in <module>
    postthis = random.choice([one,two])()
  File "C:/Users/User/Desktop/Example/example.py", line 11, in two
    return random.choice(list2) + random.choice(list3)
  File "C:UsersUserAppDataLocalProgramsPythonPython36-32librandom.py", line 256, in choice
    i = self._randbelow(len(seq))
TypeError: object of type '_io.TextIOWrapper' has no len()
>>>

I also don’t understand the error has no len(). The content of my files are just very long lists, nothing else included. Maybe somebody has an alternative solution? Thanks so much :)

Posts: 4,089

Threads: 59

Joined: Jan 2018

Reputation:
322

Apr-05-2018, 05:06 PM
(This post was last modified: Apr-05-2018, 05:09 PM by Gribouillis.)

You can use

import ast
with open('list1.txt') as infile:
    list1 = ast.literal_eval(infile.read())

The way you wrote things, list1 is an opened file object, not a list.


(Apr-05-2018, 04:47 PM)Epileptiker Wrote: I also don’t understand the error has no len().

The call to random.choice() evaluates the length of its argument. Python informs you that an open file object has no method to compute its length.

Posts: 3

Threads: 0

Joined: Apr 2018

Reputation:
0

how do i can share my query to the forum

Posts: 5

Threads: 2

Joined: Apr 2018

Reputation:
0

Oh my god it works. Awesome, thank you so much!

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)

Related videos on Youtube

Python AttributeError — What is it and how do you fix it?

05 : 20

Python AttributeError — What is it and how do you fix it?

python tutorial: TypeError: 'set' object is not subscriptable - Solved

05 : 39

python tutorial: TypeError: ‘set’ object is not subscriptable — Solved

Python Cơ bản Bài 13 | File IO in python

17 : 43

Python Cơ bản Bài 13 | File IO in python

Object Reference | Copy Objects in Python

14 : 10

Object Reference | Copy Objects in Python

Python TypeError: 'float' object is not iterable

01 : 55

Python TypeError: ‘float’ object is not iterable

How To Fix Type Error: Type Object is not Subscriptable

06 : 10

How To Fix Type Error: Type Object is not Subscriptable

TypeError : 'list' object is not callable solved in Python

00 : 31

TypeError : ‘list’ object is not callable solved in Python

TypeError: argument of type 'WindowsPath' is not iterable & 'NoneType' object is not subscriptable

01 : 59

TypeError: argument of type ‘WindowsPath’ is not iterable & ‘NoneType’ object is not subscriptable

Wrap an open stream with io.TextIOWrapper - PYTHON

01 : 38

Wrap an open stream with io.TextIOWrapper — PYTHON

Python AttributeError _io.TextIOWrapper object has no attribute split - PYTHON

01 : 05

Python AttributeError _io.TextIOWrapper object has no attribute split — PYTHON

How to read/print the ( _io.TextIOWrapper) data - PYTHON

01 : 10

How to read/print the ( _io.TextIOWrapper) data — PYTHON

Comments

  • 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)
    

Recents

Related

You need to change this:

with open(name, mode = "r") as self.message_plain:
    self.message_plain.read().encode("utf-8")

into this:

with open(name, mode="r") as input_file:
    self.message_plain = input_file.read().encode("utf-8")

The 1st with block is functionally equivalent to this:

self.message_plain = open(name, mode = "r")
self.message_plain.read().encode("utf-8")
self.message_plain.close()

which does not make sense because it just makes self.message_plain into a file object and does not save the actual contents read().

The 2nd with block is functionally equivalent to this:

input_file = open(name, mode = "r")
self.message_plain = input_file.read().encode("utf-8")
input_file.close()

which makes more sense.

Basically, you were using the with statement incorrectly, because you changed the type of self.message_plain to <class '_io.TextIOWrapper'>. You can check this by printing type(self.message_plain) after/outside of the with statement. But the encrypt_and_digest method is expecting a bytes-like sequence:

>>> help(cipher.encrypt_and_digest)
Help on method encrypt_and_digest in module Crypto.Cipher._mode_gcm:

encrypt_and_digest(plaintext, output=None) method of Crypto.Cipher._mode_gcm.GcmMode instance
    Perform encrypt() and digest() in one step.

    :Parameters:
      plaintext : bytes/bytearray/memoryview
        The piece of data to encrypt.
...

I’d like to also suggest improvements to your coding style.

  1. Put spaces after commas.

    Instead of this:

    self.cipher_text,self.tag_mac,self.salt,self.nonce = received_message
    

    Write it like this:

    self.cipher_text, self.tag_mac, self.salt, self.nonce = received_message
    
  2. Class names should use the CapWords convention.
    Instead of:

    class transmitter
    

    Change it to

    class Transmitter
    
  3. Initialize your variables to the same type you expect them to be.

    Instead of this:

    self.message_plain = True
    

    Initialize it to an empty string ("") or (None) instead.

Полный код выглядит следующим образом:

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()

И ошибка следующая:

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()

Все перепробовал, но, честно говоря, не знаю, что еще делать. Кто-нибудь знает, что может быть не так?

По сути, я хочу сохранить результат чтения определенного файла в переменной. Чтобы я мог его зашифровать. К счастью, остальная часть кода работает хорошо, только один блок кода (первый, который я задал вопросом), который представляет ошибку.

Понравилась статья? Поделить с друзьями:
  • Object has no attribute python ошибка
  • Object cannot be created on a hidden layer ошибка
  • Obdmax диагностика и расшифровка кодов ошибок скачать
  • Obd2 коды ошибок нива шевроле
  • Obd2 как сбросить ошибки на