对于作业,我创建了一段代码。 目标是打开文件并查找发件人的电子邮件地址。
#open file
fname = raw_input("Enter file name: ")
if len(fname) < 1 : fname = "mbox-short.txt"
fh = open(fname)
#look for the appropriate lines and add the in a list
names = []
for line in fh:
line = line.rstrip()
if line.startswith("From:"):
words = line.split()
names.append(words[1])
我的问题是:为什么
fname = raw_input("Enter file name: ")
if len(fname) < 1 : fname = "mbox-short.txt"
fh = open(fname)
#look for the appropriate lines and add the in a list
names = []
for line in fh:
line = line.rstrip()
if line.startswith("From:"):
words = line.split()
names.append(words[1])
工作但是
fname = raw_input("Enter file name: ")
if len(fname) < 1 : fname = "mbox-short.txt"
fh = open(fname)
text = read.fh()
#look for the appropriate lines and add the in a list
names = []
for line in text:
line = line.rstrip()
if line.startswith("From:"):
words = line.split()
names.append(words[1])
赢得&#39;?吨
我很难理解为什么我应该只使用开放而不是阅读。
由于
答案 0 :(得分:0)
首先,您需要将read.fh()
替换为fh.read()
,因为read
尚未定义且fh
是您要读取的文件对象。< / p>
其次,问题是fh.read()返回一个字符串,而不是一个行列表。因此,当你迭代时,你是按角色做的。这不是你想要的。
如果要使用fh.read(),则必须按行分割text
。因此,在for循环中使用text.split('\n')
,而不是文本。