在python中读取文件



我有一个python函数,它在一个文件中进行解析,看起来像这样:

Led Zeppelin
1979 In Through the Outdoor
-In the Evening
-South Bound Saurez
-Fool in the Rain
-Hot Dog
-Carouselambra
-All My Love
-I'm Gonna Crawl
Led Zeppelin
1969 II
-Whole Lotta Love
-What Is and What Should Never Be
-The Lemon Song
-Thank You
-Heartbreaker
-Living Loving Maid (She's Just a Woman)
-Ramble On
-Moby Dick
-Bring It on Home
Bob Dylan
1966 Blonde on Blonde
-Rainy Day Women #12 & 35
-Pledging My Time
-Visions of Johanna
-One of Us Must Know (Sooner or Later)
-I Want You
-Stuck Inside of Mobile with the Memphis Blues Again
-Leopard-Skin Pill-Box Hat
-Just Like a Woman
-Most Likely You Go Your Way (And I'll Go Mine)
-Temporary Like Achilles
-Absolutely Sweet Marie
-4th Time Around
-Obviously 5 Believers
-Sad Eyed Lady of the Lowlands

它应该在文件中读取,直到它到达新行,然后停止读取并打印它所读取的内容。但是,由于某种原因,它陷入了读取新行的无限循环中,我无法确定原因。会有一个简单的解决办法吗?也许是我忽略的一些小事?任何帮助将非常感激!

def parseData() :
    filename="testdata.txt"
    file=open(filename,"r+")
    while file.read() not in ['n', 'rn']:
        album=file.read()
    print album

read(s)的最后一行将不会返回n,而是一个空字符串,表示文件已被完全读取。

为什么不用

with open("testdata.txt") as infile:
    lines = infile.readlines()
block = ""
for line in lines:
    if line.strip() == "": break
    block += line

你可以分别分析每一行

例如,您可以一次一行一行地读取所有文件以获取所需的信息。

lines = [line.rstrip('n') for line in open(filename)]
for x in lines:
    print x

file.read()立即读取整个文件,一旦到达文件末尾,file.read()将返回一个空字符串。所以永远不会等于nrn,因此永远不会跳出while循环。

如果你想循环到一个段落的末尾,你可以使用:

paragraph = ""
for line in f:
    if line in ["n", "rn"]:
        break
    paragraph += line
print(paragraph)

您的file.read()不在['n', 'rn']中,因为它包含整个文件。您可以使用:

filename="text.txt"
block = []
for line in open(filename):
    block.append(line)
    if line in ('n', 'rn'):
        print(block)
        block=[] # remove if you want to use the content of the block
        break #stops the loop - remove if you want all blocks printed

相关内容

  • 没有找到相关文章

最新更新