使用Python 2.7在发生字符串的位置拆分文本文件

时间:2013-10-07 23:58:27

标签: python python-2.x

使用Python,如何在发生特定字符串的位置拆分文本文件?

我尝试使用.split(),但却出错:AttributeError: 'file' object has no attribute 'split'

代码:

book = open('finn.txt')
x = book.split('*** START OF THIS PROJECT GUTENBERG EBOOK HUCKLEBERRY FINN ***')

文件:finn.txt

Title: Adventures of Huckleberry Finn, Complete

Author: Mark Twain (Samuel Clemens)


*** START OF THIS PROJECT GUTENBERG EBOOK HUCKLEBERRY FINN ***

Produced by David Widger

所需输出

Produced by David Widger

1 个答案:

答案 0 :(得分:4)

您可以使用read()将整个文件读入字符串

然后使用split(...)[1]获取标记后的部分

book = open('finn.txt').read()
x = book.split('*** START OF THIS PROJECT GUTENBERG EBOOK HUCKLEBERRY FINN ***')[1]