Python 在文件打印之间输入
我试图要求用户输入f,以便打印.txt文件中的下一行。到目前为止,我只能要求1个用户输入,它将输出整个列表或列表中的特定行。我只是想用用户输入按顺序打印这些行,以便继续。以下是我目前的代码:Python 在文件打印之间输入,python,Python,我试图要求用户输入f,以便打印.txt文件中的下一行。到目前为止,我只能要求1个用户输入,它将输出整个列表或列表中的特定行。我只是想用用户输入按顺序打印这些行,以便继续。以下是我目前的代码: def wordDefinition(): fullList = input("press f for your list of words and definitions\n") if fullList == 'f': with open('study_games.txt'
def wordDefinition():
fullList = input("press f for your list of words and definitions\n")
if fullList == 'f':
with open('study_games.txt', 'r+') as f:
print(f.readline())
选择1
如果您只想让用户保持输入
,直到出现f
,然后print()
第一行,您可以执行以下操作:
def wordDefinition():
with open('study_games.txt', 'r+') as f:
fullList = input("press f for your list of words and definitions\n")
while fullList != 'f':
print("you didn't enter f!")
fullList = input("press f for your list of words and definitions\n")
print(f.readline())
这里发生的事情应该相当清楚。我们只是要求用户输入,而当输入不是'f'
时,我们打印他们没有输入'f'
并要求另一个输入
一旦他们输入了'f'
,我们就使用f.readline()
打印第一行
选择2
然而,我不确定这是你想要的。我认为您并不是在寻找txt
文件的第一行,而是在用户输入
时,要打印整个文件
这很容易做到,我们只需将f.readline()
切换到f.read()
制定代码:
def wordDefinition():
with open('study_games.txt', 'r+') as f:
fullList = input("press f for your list of words and definitions\n")
while fullList != 'f':
print("you didn't enter f!")
fullList = input("press f for your list of words and definitions\n")
print(f.read())
这样可以显示整个文件的原因如下。如果我们有一个简单的txt
文件用于测试,我们将其称为test.txt
,其内容如下:
testing
line1
line2
line3
然后当我们打电话时:
open("test.txt", "r").read()
我们将返回一个字符串,该字符串包含txt
文件的内容,其中包含分隔行的换行符(\n
):
"testing\nline1\nline2\nline3\n"
因此,我们可以将此字符串
直接传递到print()
,它将显示文件,就像在文本编辑器中看到的一样(新行代替'\n'
字符)。因此,呼吁:
print(open("test.txt", "r").read())
将返回与以前相同的内容:
testing
line1
line2
line3
因此,您可以使用相同的想法来显示'f'
的全部内容
选择3
如果您想让用户输入'f'
并只打印出一行,然后等待下一行的另一个输入,直到文件结束,您只需要将第一个代码放入for循环
。使用迭代文件对象的for循环
,可以非常轻松地循环文件行
所以我们需要做的就是在第一个code
中添加一个for循环
:
def wordDefinition():
with open('study_games.txt', 'r+') as f:
for line in f:
fullList = input("press f for your list of words and definitions\n")
while fullList != 'f':
print("you didn't enter f!")
fullList = input("press f for your list of words and definitions\n")
print(line)
在fullList=input(…)
之前打开文件,但这只能工作一次,因为您没有while
循环。如果我添加while循环,它只会继续运行,并且只打印.txt文档的第一行。这就是我困惑的地方,因为我无法让它停止打印空行,然后我不知道如何让它在第二个f输入后打印第二行。对不起,我不擅长写我的意思。我需要做的是,当他们按f+enter键时,打印第一行,然后当他们再次按f+enter键时,打印第二行,依此类推,不管文本文件中有多少行。我已经按照您刚才解释的方式更新了答案(选项3
)。如果有帮助,请投票并接受!:)