简体   繁体   English

我如何在 python 的 while 循环中逐行打印 a.txt 文件中的每一行

[英]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.

相关问题 如何仅从txt文件打印一行? (蟒蛇) - How to only print one line from a txt file? (python) 如何在一行中用python打开.txt文件 - how do you open .txt file in python in one line 无论如何在 python 中是否有从 a.txt 文件中随机检索一行,然后打印它并多次执行此操作而不重复同一行? - Is there anyway in python to retrieve a line from a .txt file randomly, then print it and do this multiple times without repeating the same one? 如何在txt文件中打印每行的第一个单词? - How do I print the 1st word of each line in a txt file? 如何在.txt文件中保存列表的每个元素,每行一个? - How do you save each element of a list in a .txt file, one per line? 如何在一行中使用for循环在python中声明列表? - How do I declare list in python using for loop in one line? 如何在python中打印字典? (在单独的一行上一个一个地打印) - How do I print a dictionary in python? (Prints it one by one on a separate line) 如何在python中打印每个循环的所有结果一次 - How to print all the result of each loop one time in python 如何从python中的.txt文件读取特定行? - How to read one particular line from .txt file in python? 如何在一行中的列表中打印每个字符串的首字母? - How do I print the first letter of each string in a list in one line?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM