[英]Outputting a list as a text file
我試圖改進我朋友的 Python“Twitch 帳戶檢查器”(基本上從文本文件中獲取用戶名列表並檢查它們是否可用或在 Twitch.tv 上使用)。 我打算以一種將可用用戶名輸出到文本文件(與原始列表相同的位置)的方式對其進行改進。 我實際上是在搜索 Stack Overflow 並找到了一篇“解釋”如何將列表(我將可用的用戶名放入單獨的列表)實際輸出到文本文件中的帖子。
運行腳本時,它可以正常工作到應該保存可用用戶名的部分。 然后,我收到以下錯誤:
Traceback (most recent call last):
File "multithreadtwitchchecker.py", line 44, in <module>
output_available_usernames('availableusernames.txt')
File "multithreadtwitchchecker.py", line 37, in output_available_usernames
AVAILABLE_USERNAMES = f.write(AVAILABLE_USERNAMES.split('\n'))
AttributeError: 'list' object has no attribute 'split'
這是代碼:
from multiprocessing.pool import ThreadPool
import re
import requests
import sys
try:
input = raw_input
except NameError:
pass
TWITCH_URL = "https://www.twitch.tv/{username}"
TWITCH_REGEX = re.compile(r"^[a-zA-Z0-9_]{4,25}$")
MAX_THREADS = 25
MESSAGES = {True: "Available", False: "Taken"}
AVAILABLE_USERNAMES = []
def read_valid_usernames(filename):
"""Reads a list of usernames and filters out invalid ones."""
try:
with open(filename, "r") as fin:
return [username for username in map(str.strip, fin) if TWITCH_REGEX.match(username)]
except IOError:
sys.exit("[!] '{}' - Invalid File".format(filename))
def username_available(username):
"""Checks if a 404 response code is given when requesting the profile. If it is, it is presumed to be available"""
try:
return username, requests.get(TWITCH_URL.format(username=username)).status_code == 404
AVAILABLE_USERNAMES.append(username)
except Exception as e:
print(e)
def output_available_usernames(filename):
"""Gets a filename to output to and outputs all the valid usernames to it"""
global AVAILABLE_USERNAMES
f = open(filename, 'w')
AVAILABLE_USERNAMES = f.write(AVAILABLE_USERNAMES.split('\n'))
usernames = read_valid_usernames(input("Enter path to list of usernames: "))
for username, available in ThreadPool(MAX_THREADS).imap_unordered(username_available, usernames):
print("{:<{size}}{}".format(username, MESSAGES.get(available, "Unknown"), size=len(max(usernames, key=len)) + 1))
output_available_usernames('availableusernames.txt')
好吧,寫入文件可以這樣完成:
def output_available_usernames(filename):
global AVAILABLE_USERNAMES
with open(filename, 'w') as f:
for name in AVAILABLE_USERNAMES:
f.write(name + '\n')
正如 jonrsharpe 所說, split
正朝着錯誤的方向發展。
但是,您的代碼現在有一個更深層次的問題。 在return
語句之后附加到AVAILABLE_USERNAMES
,這樣代碼永遠不會執行,並且AVAILABLE_USERNAMES
將始終為空。 你想要這樣的東西:
def username_available(username):
"""Checks if a 404 response code is given when requesting the profile. If it is, it is presumed to be available"""
try:
if requests.get(TWITCH_URL.format(username=username)).status_code == 404:
AVAILABLE_USERNAMES.append(username)
return username, True
else:
return username, False
except Exception as e:
print(e)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.