Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/tfs/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.2-readline()正在跳过源文件中的行_Python_Readline_Accumulator - Fatal编程技术网

Python 3.2-readline()正在跳过源文件中的行

Python 3.2-readline()正在跳过源文件中的行,python,readline,accumulator,Python,Readline,Accumulator,我有一个用多行创建的.txt文件 当我使用计数累加器运行for循环时,它跳过行 它跳过顶行,从第二行开始,打印第四行,第六行,等等 我错过了什么 ** for your reading pleasure** def main(): # Open file line_numbers.txt data_file = open('line_numbers.txt', 'r') # initialize accumulatior count = 1 # Re

我有一个用多行创建的.txt文件

当我使用计数累加器运行for循环时,它跳过行

它跳过顶行,从第二行开始,打印第四行,第六行,等等

我错过了什么

** for your reading pleasure**
def main():
    # Open file line_numbers.txt
    data_file = open('line_numbers.txt', 'r')

    # initialize accumulatior
    count = 1


    # Read all lines in data_file
    for line in data_file:
        # Get the data from the file
        line = data_file.readline()

        # Display data retrieved
        print(count, ": ", line)

        # add to count sequence
        count += 1

是否尝试将“line=data_file.readline()”一起删除?我怀疑“for line in data_file:”也是一个readline操作。

您的for循环正在迭代数据_文件,您的readline()正在与之竞争。删除代码的
line=data\u file.readline()
行以获得此结果:

# Read all lines in data_file
count = 1
for line in data_file:
    # Display data retrieved
    print(count, ": ", line)

    # add to count sequence
    count += 1

for line in data_file
已经为您获取了每行的文本-随后对readline的调用将获取以下行。换句话说,删除对readline的调用将实现您想要的功能。同时,您不需要自己跟踪累加器变量—python有一种使用
enumerate
的内置方法—换句话说:

data_file = open('line_numbers.txt', 'r')
for count, line in enumerate(data_file):
    ...

我想@Shelhammer已经搞定了。我想很明显“in”是个读物。是的。现在不是跳过,而是计算输出上的空行?因此,与其使用1-5(返回1-11),不如使用
和open('line_numbers.txt')作为数据文件来更好地改进这一点:
+1确实用于enumerate()。不要忘记从零开始的数字,所以当打印供人使用时,您通常希望在计数中加一。大多数人对基于1的编号更满意。谢谢大家。我在一个班上,这是从“基础”开始的教学,但我一定会把它记在我的笔记里!!