在Python的for循环中读取下一行

huangapple go评论93阅读模式
英文:

Reading next line in python in for loop

问题

  1. 我想每次for循环继续时读取文件中的下一行。
  2. 以下是代码:
  3. ```python
  4. file1 = open('users.txt', 'r')
  5. lines = file1.readlines()
  6. for i in range(len(lines)):
  7. file1 = open('users.txt', 'r')
  8. lina = file1.readline()
  9. parts = lina.strip().split(':')
  10. print(parts[0])
  11. print(parts[1])
  12. continue

顺便说一下,i = 3,因为文件总共有3行!
因此,这段代码的输出是:

  1. user1
  2. user1pass
  3. user1
  4. userpass
  5. user1
  6. userpass

我想要的是:

  1. user1
  2. user1pass
  3. user2
  4. user2pass
  5. user3
  6. user3pass
  1. <details>
  2. <summary>英文:</summary>
  3. I want to read the next line in the file every time the for loop continues.
  4. Here is the code

file1 = open('users.txt', 'r')
lines = file1.readlines()
for i in range(len(lines)):
file1 = open('users.txt', 'r')
lina=file1.readline()
parts = lina.strip().split(':')
print(parts[0])
print(parts[1])
continue

  1. btw i = 3 because the file consists of total 3 lines!
  2. So the output of this code is:

user1
user1pass
user1
userpass
user1
userpass

  1. What i want is:

user1
user1pass
user2
user2pass
user3
user3pass

  1. </details>
  2. # 答案1
  3. **得分**: 4
  4. ```python
  5. 正如评论者所提到的,你正在打开文件并且在循环的每次迭代中仅使用第一行。你可以简化这个过程,只需直接迭代行而不必担心索引。
英文:

As the commenter mentioned, you are opening the file and only using the first line on every iteration of the loop. You can simplify this a lot and just iterate over the lines themselves without worrying about the index

  1. with open(&#39;users.txt&#39;, &#39;r&#39;) as file1:
  2. for line in file1:
  3. parts = line.strip().split(&#39;:&#39;)
  4. print(parts[0])
  5. print(parts[1])

huangapple
  • 本文由 发表于 2023年3月7日 21:04:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75662353.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定