Tag Archives: Python TypeError

Python TypeError: ‘int’ object is not iterable

Use a loop to print out each name in the list in turnHello, xxx!

——————————————————–

L = [‘Bart’, ‘Lisa’, ‘Adam’]
x = len(L)

for i in range(x):

print(‘Hello,’, L[i])

——————————————————–

Here, if you use for i in x directly, the compiler reports an error.TypeError: ‘int’ object is not iterable:

Traceback(mostrecentcalllast):
File”main.py”,line5,in<module>
foriinx:
TypeError:’int’objectisnotiterable

The reason for this problem is that you cannot iterate directly with int, but must use the range method, i.e. range(x).

[Solved] Python TypeError: ‘int’ object is not callable

TypeError:’int’ object is not callable

The reason for this error is simple

Look at the following program:

1  def loss(a,b):
 2      return a- b
 3  
4 loss = 0
 5 loss = loss(5,2)+1

Error positioning:

loss = loss(5,2)+1
TypeError:’int’ object is not callable

 

the reason:

Function name loss

Variable name loss

coincide! ! !

 

Python TypeError: file must have ‘read’ and ‘readline’ attributes

Python Error: TypeError: file must have ‘read’ and ‘readline’ attributes

Error when running serialization (pickle) related functions: TypeError: file must have ‘read’ and ‘readline’ attributes

Code above.

>>> fp = open("a.txt","r+")
>>> import pickle
>>> pickle.load("fp")#error
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: file must have 'read' and 'readline' attributes

Cause analysis: the parameter in the load () method is wrongly written. If there is one more “” and it can be removed

Solution:

Change to the following method

>>> fp = open("a.txt","rb+")
>>> import pickle
>>> pickle.load(fp)#Serialized Print Results
['apple', 'mango', 'carrot']

Python TypeError: unbound method a() must be called with A instance as first argument (go…

TypeError: unbound method a() must be called with A instance as first argument (got nothing instead)

# encoding: utf-8

import time
import threading

class test:

    def follow(self,thefile):
        thefile.seek(0,2)
        while True:
            line = thefile.readline()
            if not line:
                time.sleep(0.1)
                continue
                yield line

if __name__ == '__main__':

    # obj = test()
    file1 = 'log.txt'
    file2 = 'result.txt'
    logfile = open(file2,"r")
    # loglines = obj.follow(logfile)
    loglines = test.follow(logfile)
    for line in loglines:
        print line,

output

C:\Python27\python.exe C:/Users/sys_syspifarm/.ssh/MagicBox/source/test.py
Traceback (most recent call last):
File “C:/Users/sys_syspifarm/.ssh/MagicBox/source/test.py”, line 44, in <module>
loglines = test.follow(logfile)
TypeError: unbound method follow() must be called with test instance as first argument (got file instance instead)

Process finished with exit code 1

Reason for error: The function a() is not a static method, so it needs to be instantiated before it can be used, corrected as follows.

# encoding: utf-8

import time
import threading

class test:

    def follow(self,thefile):
        thefile.seek(0,2)
        while True:
            line = thefile.readline()
            if not line:
                time.sleep(0.1)
                continue
                yield line

if __name__ == '__main__':

    obj = test()
    file1 = 'log.txt'
    file2 = 'result.txt'
    logfile = open(file2,"r")
    loglines = obj.follow(logfile)
    # loglines = test.follow(logfile)
    for line in loglines:
        print line,

Obj = test() needs to instantiate the method

TypeError: strptime() argument 1 must be str, not bytes

About TypeError:strptime()argument1mustbestr,notbytes Explanation
When using datetime.strptime(s,fmt) to output the result date result, an error occurs

TypeError:strptime()argument1mustbestr,notbytes

My source code is as follows

def datestr2num(s):
return datetime.strptime(s,“%d-%m-%Y”).date().weekday()

dates=np.loadtxt(‘data.csv’,delimiter=’,,usecols=(1,),converters={1: datestr2num},unpack=True)

data.csv:

When the compiler opens the data.csv file, the second column of array values in the table is extracted and returned to dates, the second column of values is a date format string, but because we are opening the second column of values in binary encoding format is, the returned value bytes string bytes, so it needs to be string, then the string is decoded with the function decode(‘asii ‘), into string format.

def datestr2num(s):
return datetime.strptime(s.decode(‘ascii’),“%d-%m-%Y”).date().weekday()

dates=np.loadtxt(‘data.csv’,delimiter=’,,usecols=(1,),converters={1: datestr2num},unpack=True)

 

lineis a bytestring,because you opened the file in binary mode. You’ll need to decode the string; if it is a date string matching the pattern,you can simply use ASCII:

 time.strptime(line.decode('ascii'), '%Y-%m-%d ...')

You can add a'ignore'argumentto ignore anything non-ASCII,but chances are the line won’t fit your date format then anyway.

Note that you cannot pass a value that containsmorethan the parsed format in it; a line with other text on itnotexplicitly covered by thestrptime()pattern willnotwork,whatever codec you used.

And if your input really varies that widely in codecs,you’ll need to catch exceptions one way or another anyway.

Aside from UTF-16 or UTF-32,I wouldnotexpect you to encounter any codecs that use differentbytesfor the arabic numerals. If your input really mixes multi-byte and single-byte codecs in one file,you have a bigger problem on your hand,notin the least because newline handling willbemajorly messed up.

 

 

TypeError: write() argument must be str, not bytes

ModuleNotFoundError: No module named ‘jsonpath’

The new situation after the last blog about no jsonpath solution

During execution, the console prompts the following error code:

TypeError: write() argument must be str, not bytes

As a beginner, I didn’t understand many copies on CSDN. Then I found the answer I wanted and solved my problem on stackoverflow

Link: typeerror: must be STR, not bytes

The question is like this, cut a picture

The answer is also to the point, cut a picture

The output file should be in binary mode

There is no problem with the console execution after modification

Then I found out from the python document query:

Python: open/file operation
F = open (‘/ TMP/Hello’,’w ‘)
#open (path + file name, read-write mode)
#read-write mode: R read-only, R + read-write, w New (will cover the original file), a append, B binary file. Common modes