简体   繁体   English

.readlines()[n] 错误

[英]Error with .readlines()[n]

I'm a beginner with Python.我是 Python 的初学者。 I tried to solve the problem: "If we have a file containing <1000 lines, how to print only the odd-numbered lines? ".我试图解决这个问题:“如果我们有一个包含 <1000 行的文件,如何只打印奇数行?”。 That's my code:那是我的代码:

with open(r'C:\Users\Savina\Desktop\rosalind_ini5.txt')as f:
   n=1
   num_lines=sum(1 for line in f)
   while n<num_lines:
         if n/2!=0:
                 a=f.readlines()[n]
                 print(a)
         break
    n=n+2

where n is a counter and num_lines calculates how many lines the file contains.其中n是一个计数器, num_lines计算文件包含多少行。 But when I try to execute the code, it says:但是当我尝试执行代码时,它说:

"a=f.readlines()[n]
 IndexError: list index out of range"

Why it doesn't recognize n as a counter?为什么它不将n识别为计数器?

You have the call to readlines into a loop, but this is not its intended use, because readlines ingests the whole of the file at once, returning you a LIST of newline terminated strings.您可以调用readlines进入循环,但这不是它的预期用途,因为readlines摄取整个文件,返回一个以换行符结尾的字符串的列表。

You may want to save such a list and operate on it您可能希望保存这样的列表并对其进行操作

list_of_lines = open(filename).readlines() # no need for closing, python will do it for you
odd = 1
for line in list_of_lines:
    if odd : print(line, end='')
    odd = 1-odd

Two remarks:两点说明:

  1. odd is alternating between 1 (hence true when argument of an if ) or 0 (hence false when argument of an if ), odd1 (因此在if参数时为真)或0 (因此在if参数时为假)之间交替,
  2. the optional argument end='' to the print function is required because each line in list_of_lines is terminated by a new line character, if you omit the optional argument the print function will output a SECOND new line character at the end of each line. print函数的可选参数end=''是必需的,因为list_of_lines每一行都以换行符终止,如果省略可选参数, print函数将在每行的末尾输出第二个换行符。

Coming back to your code, you can fix its behavior using a回到您的代码,您可以使用

f.seek(0)

before the loop to rewind the file to its beginning position and using the f.readline() (look, it's NOT readline**S** ) method inside the loop, but rest assured that proceding like this is.在循环之前将文件倒回其开始位置并在循环内使用f.readline() (看,它不是readline**S** )方法,但请放心,像这样进行。 let's say, a bit unconventional...让我们说,有点非常规......

Eventually, it is possible to do everything you want with a one-liner最终,可以用单线做你想做的一切

print(''.join(open(filename).readlines()[::2]))

that uses the slice notation for list s and the string method .join()使用切片符号表示列表字符串方法.join()

Well, I'd personally do it like this:好吧,我个人会这样做:

def print_odd_lines(some_file):
    with open(some_file) as my_file:
        for index, each_line in enumerate(my_file):  # keep track of the index of each line
            if index % 2 == 1:  # check if index is odd
                print(each_line)  # if it does, print it

if __name__ == '__main__':
    print_odd_lines('C:\Users\Savina\Desktop\rosalind_ini5.txt')

Be aware that this will leave a blank line instead of the even number.请注意,这将留下一个空行而不是偶数。 I'm sure you figure how to get rid of it.我相信你知道如何摆脱它。

This code will do exactly as you asked:此代码将完全按照您的要求执行:

with open(r'C:\Users\Savina\Desktop\rosalind_ini5.txt')as f:
    for i, line in enumerate(f.readlines()):   # Iterate over each line and add an index (i) to it.
        if i % 2 == 0:       # i starts at 0 in python, so if i is even, the line is odd
            print(line)

To explain what happens in your code:解释代码中发生的事情:

A file can only be read through once.一个文件只能被读取一次。 After that is has to be closed and reopened again.之后必须关闭并重新打开。

You first iterate over the entire file in num_lines=sum(1 for line in f) .您首先在num_lines=sum(1 for line in f)遍历整个文件。 Now the object f is empty.现在对象f是空的。

If n is odd however, you call f.readlines() .但是,如果 n 是奇数,则调用f.readlines() This will go through all the lines again, but none are left in f .这将再次遍历所有行,但f没有任何行。 So every time n is odd, you go through the entire file.因此,每次 n 为奇数时,您都会遍历整个文件。 It is faster to go through it once (as in the solutions offered to your question).通过一次会更快(如为您的问题提供的解决方案)。

As a fix, you need to type作为修复,您需要键入

f.close()
f = open(r'C:\Users\Savina\Desktop\rosalind_ini5.txt')

everytime after you read through the file, in order to get back to the start.每次阅读完文件后,才能回到起点。

As a side note, you should look up modolus % for finding odd numbers.作为旁注,您应该查找 modolus % 以查找奇数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM