使用while循环函数从文本文件Python返回字符串

时间:2015-05-26 22:50:25

标签: python file while-loop

此函数包含一个文件“file.txt”,其中包含txt“Hello World!”我需要做的是打开文件并使用while循环来构建并返回文件中的短语和最后一个单词(“World!”)x在新行上的次数。

while循环是必不可少的

没有while循环的任何其他方式也会有所帮助

def echo(fname, x):
    fname = open("file.txt",'r')
    text = fname.read()
    return text
    i=1
    while i <= x:
        return text[:6]
        i +=1

以下是问题和应该产生的结果。

编写一个函数,它接受一个代表文件名的字符串作为参数和一个数字x。打开文件并使用while循环并返回包含文件中的短语和最后一个单词x次的字符串。

def echo(fname, x):
"""
>>>echo("file.txt", 2)
"Hello World!:\\nWorld!\\nWorld!\\n
>>> echo("file.txt", 4)
"Hello World!:\\nWorld!\\nWorld!\\nWorld!\\nWorld!\\n
"""

2 个答案:

答案 0 :(得分:1)

假设您的文件总是有一行:

def echo(filename, repeats):
    with open(filename) as f:
        txt = f.read()  # this is normally ugly, but since we're presupposing
                        # one-line files, let's run with it....
    last_word = txt.split()[-1]
    result = "\n".join([txt] + [last_word] * repeats)
    return result

在这里使用while循环很愚蠢。不要这样做。

答案 1 :(得分:1)

如果你真的想要while循环

def echo(fname, x):
    with open(fname) as f:
        line = f.readline()

    retlst = [line]

    i = 0
    words = line.split()
    while i < x:
        retlst.extend(words[-1:])
        i += 1

    return '\n'.join(retlst)

print echo("filewhl.txt", 3)