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

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

Reading next line in python in for loop

问题

我想每次for循环继续时读取文件中的下一行。
以下是代码:

```python
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

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

user1
user1pass
user1
userpass
user1
userpass

我想要的是:

user1
user1pass
user2
user2pass
user3
user3pass

<details>
<summary>英文:</summary>

I want to read the next line in the file every time the for loop continues.
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





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

user1
user1pass
user1
userpass
user1
userpass

What i want is:

user1
user1pass
user2
user2pass
user3
user3pass


</details>


# 答案1
**得分**: 4

```python
正如评论者所提到的,你正在打开文件并且在循环的每次迭代中仅使用第一行。你可以简化这个过程,只需直接迭代行而不必担心索引。

英文:

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

with open(&#39;users.txt&#39;, &#39;r&#39;) as file1:
    for line in file1:
        parts = line.strip().split(&#39;:&#39;)
        print(parts[0])
        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:

确定