[英]Outputting a list as a text file
I was trying to improve my friend's Python 'Twitch account checker' (basically gets a list of usernames from a text file and checks if they're available or taken on Twitch.tv).我试图改进我朋友的 Python“Twitch 帐户检查器”(基本上从文本文件中获取用户名列表并检查它们是否可用或在 Twitch.tv 上使用)。 I was going to improve it in a way that it would output the available usernames into a text file (in the same location as the original list).
我打算以一种将可用用户名输出到文本文件(与原始列表相同的位置)的方式对其进行改进。 I was actually searching Stack Overflow and found a post which 'explained' how to actually output a list (I put the available usernames into a separate list) into a text file.
我实际上是在搜索 Stack Overflow 并找到了一篇“解释”如何将列表(我将可用的用户名放入单独的列表)实际输出到文本文件中的帖子。
When running the script, it works fine up to the part where it's supposed to save the available usernames.运行脚本时,它可以正常工作到应该保存可用用户名的部分。 Then, I get the following error:
然后,我收到以下错误:
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'
Here's the code:这是代码:
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')
Well, writing to a file can be done like this:好吧,写入文件可以这样完成:
def output_available_usernames(filename):
global AVAILABLE_USERNAMES
with open(filename, 'w') as f:
for name in AVAILABLE_USERNAMES:
f.write(name + '\n')
As jonrsharpe said, split
is going in the wrong direction.正如 jonrsharpe 所说,
split
正朝着错误的方向发展。
However, your code has a deeper problem right now.但是,您的代码现在有一个更深层次的问题。 You append to
AVAILABLE_USERNAMES
after the return
statement, so that code never executes, and AVAILABLE_USERNAMES
will always be empty.在
return
语句之后附加到AVAILABLE_USERNAMES
,这样代码永远不会执行,并且AVAILABLE_USERNAMES
将始终为空。 You instead want something like this:你想要这样的东西:
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.