在python中进行切片,在复制和使用一行后前进n行

在python中进行切片,在复制和使用一行后前进n行,python,list,slice,Python,List,Slice,我正在编写脚本,请参见此处: from pysnap import Snapchat import time usnlist = raw_input('Enter file name: ') s = Snapchat() def filter(username, password): s.login(username, password) with open (usnlist, 'r') as file: for line in file:

我正在编写脚本,请参见此处:

from pysnap import Snapchat
import time

usnlist = raw_input('Enter file name: ')

s = Snapchat()

def filter(username, password):
    s.login(username, password)
    with open (usnlist, 'r') as file:
        for line in file:
            ok = False
            while not ok:
                try:
                    resp = s.add_friend(line.rstrip("\n"))
                    if 'object' in resp.keys():
                        # 'object' is contained within resp as a key
                        if resp['object']['type']:
                            # type is 1
                            with open ('private.txt', 'a') as f: f.write(resp['object']['name']+"\n")
                            print line.rstrip("\n") + "'s",
                            print "privacy settings are set to: FRIENDS"
                        else:
                            # type is 0
                            with open ('n-private.txt', 'a') as f: f.write(resp['object']['name']+"\n")
                            print line.rstrip("\n") + "'s",
                            print "privacy settings are set to: EVERYONE"
                        s.delete_friend(line)
                    else:
                        # no object in resp, so it's an invalid username
                        print line.rstrip("\n") + " is not a valid username"
                    ok = True
                except:
                    time.sleep(5)
                    print "SNAPCHAT SERVER OVERLOAD - HOLD ON."

username = raw_input('Enter username: ')
password = raw_input('Enter password: ')

filter(username, password)

我现在想要的是能够输入一个值,我们称之为
n
当我输入
n
时,机器人只会刮取每一行
n

比如说<代码>N=2。 机器人现在只会从列表中每隔一秒抓取并输入用户名

我想出了一些东西,比如将[0::2]添加到:
resp=s.add\u friend(line.rstrip(“\n”)
结果是:
resp=s.add\u friend(第[0::2]行).rstrip(“\n”)

但这不起作用,bot直接打印“SNAPCHAT服务器过载-请稍候”。 不查名字

我的想法是:

http://stackoverflow.com/questions/18155682/gathering-every-other-string-from-list-line-from-file
但是提供的信息不足以让这一切正常进行。 我使用python 2.7.8

我希望有一种方法告诉python:“获取文件中的每一行” 因为这基本上就是我想要的


如果有人能帮忙,那就太好了

您尝试的是将行而不是文件切片。文件不支持切片,但模块具有切片任意可编辑文件的功能:

import itertools
for line in itertools.islice(file, None, None, n):
    do_whatever_with(line)

前两个参数是start和stop;这些参数的值
None
表示输入的开始和结束,因为不能像在常规切片中那样省略它们。第三个参数是步骤。

您尝试的是分割行,而不是文件。文件不支持切片,但模块具有切片任意可编辑文件的功能:

import itertools
for line in itertools.islice(file, None, None, n):
    do_whatever_with(line)

前两个参数是start和stop;这些参数的值
None
表示输入的开始和结束,因为不能像在常规切片中那样省略它们。第三个参数是步骤。

要获取文件中的每N行,请替换为:

for line in file:
与:


要获取文件中的每N行,请替换以下内容:

for line in file:
与:


先生,这是你的功劳。先生,这是你的功劳