[英]TypeError: unsupported operand type(s) for +: 'int' and 'str' when trying to 'print'
[英]TypeError: unsupported operand type(s) for +: 'int' and 'list' when trying to split a text file
該程序用於加載一個文本文件,該文本文件的每一行都有一個代理。 然后,它要求用戶輸入他們需要將代理放入哪些分隔中。 例如,如果我在100個單獨的行中的文本文件中有100個代理,並說我需要5個10包代理和2個25包代理,則程序將輸出總共7個文本文件,這些文本文件加起來100個代理。
filename = input('Enter a file name: ')
with open(filename) as f: ###load text file
line_count = 0
for line in f:
line_count += 1
print("Number of proxies: " + str(line_count)) ###count proxies
pack10 = int(input("10 packs? ")) ###designate packs
pack25 = int(input("25 packs? "))
pack50 = int(input("50 packs? "))
pack100 = int(input("100 packs? "))
total = pack10*10 + pack25*25 + pack50*50 + pack100*100 ###calculate total proxies needed
packs = ([pack10]*10) + ([pack25]*25) + ([pack50]*50) + ([pack100]*100)
def split_list(filename, sizes): ###chunking of list
with open(filename) as f:
content = f.readlines()
new_content = []
start = 0
for size in sizes:
stop = start + size
new_content.append(content[start:stop])
start += size
return new_content
splitted_list = split_list(filename, [packs])
if line_count < total:
print("You need " + str((total - line_count)) + " more proxies") ###ensure right amount of proxies
else:
for i, l in enumerate(splitted_list): ###chunk proxies
with open('{}.txt'.format(i), 'w') as f:
f.writelines(l) #output text files
print("Complete")
這是錯誤:
Traceback (most recent call last):
File "c:\Users\Username\Desktop\New Folder\proxies\splitter.py", line 28, in <module>
splitted_list = split_list(filename, [packs])
File "c:\Users\Username\Desktop\New Folder\proxies\splitter.py", line 22, in split_list
stop = start + size
TypeError: unsupported operand type(s) for +: 'int' and 'list'
不知道該怎么做,該程序工作正常,當我更換[packs]
在splitted_list = split_list(filename, [packs])
與[5, 3, 2]
例如。
從此行刪除方括號:
splitted_list = split_list(filename, [packs])
變成:
splitted_list = split_list(filename, packs)
而不是傳入大小數組,而是將數組包裝在額外的數組層中,因此,大小的第一個元素實際上就是您想要的。 例如。 而不是傳遞[2, 2, 2, 5, 5, 5]
,而是傳遞[[2, 2, 2, 5, 5, 5]]
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.