英文:
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('users.txt', 'r') as file1:
for line in file1:
parts = line.strip().split(':')
print(parts[0])
print(parts[1])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论