[英]How do i print each line in a .txt file one by one in a while loop in python
Ok so, lets say i have data from a.txt file here:好的,假设我在这里有来自 a.txt 文件的数据:
ToddShields74
GeorgeGutierrez18
ReginaHenry71
JohnBlair34
PaigeKirby47
...
Now, i want a python code that will print each line one by one in a loop, for example:现在,我想要一个 python 代码,它将在循环中逐行打印每一行,例如:
while/if (imagine some random thing here):
print(line1 of the text file)
(obviously not a real code but presenting what i need.) (显然不是真正的代码,而是展示我需要的东西。)
Then the next loop should print the next line, and the next, until it has printed all the lines in the file然后下一个循环应该打印下一行,再下一行,直到它打印了文件中的所有行
Help is really appreciated!非常感谢您的帮助!
You can simply open the file and iterate through it:您可以简单地打开文件并遍历它:
file_name = "file.txt"
with open(file_name) as f:
for line in f:
print(line.strip()) # strip to remove extra newline after each line
# whatever else you want to do
You can use a regular expression and sort it by the new line \n character您可以使用正则表达式并按换行符 \n 字符对其进行排序
import re
txt = your text here
x = re.findall(".+\n", txt)
The .+ will get anything that comes before a new line, \n. .+ 将获取新行之前的任何内容,\n。
This will return a list of all matches seperated by line and you can loop through them.这将返回按行分隔的所有匹配项的列表,您可以遍历它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.